C语言获取文件中单词并进行处理

该博客介绍了一个使用C语言实现的读取文件单词的函数process,它能通过回调函数processer处理读取到的单词。适用于进行hash函数测试,通过自定义isWord函数筛选特定字符组成的单词。
/******************************************************
 *
 *         follows begin the word get process
 *
 ******************************************************/
bool isWord(char c)
{
        if ((('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z')) || ('-' == c)) {
                return true;
        }
 
        return false;
}
 
struct word_geter_engine {
        char * buffer;          /* contain the words */
        char * current;         /* where we reach in the buffer */
        char * end;             /* the last position + 1 */
        int bufferSize;         /* the capacity of the buffer */
        char wordBuf[WORDLEN];  /* store the word have got */
        bool needFill;          /* indicate whether need fill the buffer */
};
 
bool initStorer(int capacity, struct word_geter_engine * engine)
{
        engine->buffer = malloc(capacity);
        if (NULL == engine->buffer) {
                return false
以下是一个简单的C语言程序,用于统计文本文件单词的频度: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX_WORD_LEN 50 // 最大单词长度 #define MAX_WORDS 10000 // 最大单词数 int main(int argc, char *argv[]) { char filename[100]; // 文件名 char word[MAX_WORD_LEN + 1]; // 当前单词 char words[MAX_WORDS][MAX_WORD_LEN + 1]; // 所有单词 int freq[MAX_WORDS]; // 单词频度 int n = 0; // 单词数 int i, j, k; // 循环计数器 FILE *fp; // 文件指针 // 获取文件名 if (argc < 2) { printf("请输入文件名:"); scanf("%s", filename); } else { strcpy(filename, argv[1]); } // 打开文件 fp = fopen(filename, "r"); if (fp == NULL) { printf("无法打开文件 %s\n", filename); exit(1); } // 读取所有单词 while (fscanf(fp, "%s", word) == 1) { // 将单词转换成小写 for (i = 0; word[i] != '\0'; i++) { word[i] = tolower(word[i]); } // 检查单词是否已经出现过 for (i = 0; i < n; i++) { if (strcmp(words[i], word) == 0) { freq[i]++; break; } } // 如果单词是新出现的,则加入单词列表 if (i == n) { strcpy(words[n], word); freq[n] = 1; n++; } } // 关闭文件 fclose(fp); // 输出所有单词及其频度 for (i = 0; i < n; i++) { printf("%s:%d\n", words[i], freq[i]); } return 0; } ``` 该程序的基本思路是: 1. 打开文件; 2. 逐个读取文件中的单词将其转换成小写形式; 3. 检查该单词是否已经出现过,如果是则增加其频度,否则将其加入单词列表; 4. 关闭文件; 5. 输出所有单词及其频度。 需要注意的是,该程序假设单词之间用空格或换行符分隔,且不考虑标点符号对单词的影响。如果需要更精确地统计单词,需要对程序进行一定的修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值