请帮我写个计算文件夹中每个txt文件中的词频代码
时间: 2023-03-28 15:03:37 浏览: 52
好的,以下是计算文件夹中每个txt文件中的词频的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#define MAX_WORD_LEN 50
#define MAX_FILE_NUM 100
#define MAX_WORD_NUM 10000
typedef struct {
char word[MAX_WORD_LEN];
int count;
} Word;
int cmp(const void *a, const void *b) {
return ((Word *)b)->count - ((Word *)a)->count;
}
int main() {
DIR *dir;
struct dirent *entry;
char *folder = "./folder"; // 文件夹路径
char *suffix = ".txt"; // 文件后缀
char filename[100];
FILE *fp;
char word[MAX_WORD_LEN];
Word words[MAX_WORD_NUM];
int word_num = ;
int file_num = ;
int i, j, k;
// 打开文件夹
if ((dir = opendir(folder)) == NULL) {
printf("Cannot open folder.\n");
return 1;
}
// 遍历文件夹中的文件
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, suffix) != NULL) {
// 构造文件路径
sprintf(filename, "%s/%s", folder, entry->d_name);
// 打开文件
if ((fp = fopen(filename, "r")) == NULL) {
printf("Cannot open file: %s\n", filename);
continue;
}
// 统计词频
while (fscanf(fp, "%s", word) != EOF) {
// 将单词转换为小写
for (i = ; word[i] != '\'; i++) {
if (word[i] >= 'A' && word[i] <= 'Z') {
word[i] += 'a' - 'A';
}
}
// 查找单词是否已经存在
for (i = ; i < word_num; i++) {
if (strcmp(words[i].word, word) == ) {
words[i].count++;
break;
}
}
// 如果单词不存在,则添加新单词
if (i == word_num) {
strcpy(words[i].word, word);
words[i].count = 1;
word_num++;
}
}
// 关闭文件
fclose(fp);
// 文件数加1
file_num++;
}
}
// 关闭文件夹
closedir(dir);
// 按词频排序
qsort(words, word_num, sizeof(Word), cmp);
// 输出结果
printf("共处理了 %d 个文件,%d 个单词\n", file_num, word_num);
printf("词频前10的单词如下:\n");
for (i = ; i < 10 && i < word_num; i++) {
printf("%s: %d\n", words[i].word, words[i].count);
}
return ;
}
```
请注意,这只是一个简单的示例代码,可能存在一些问题,需要根据实际情况进行修改和完善。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)