统计文本文件中的每一个单词出现的次数

本文介绍了一种利用Python标准库collections中的Counter函数统计文本文件中词汇出现频率的方法。通过读取文本文件,将文件内容分割成单词列表,并使用Counter函数进行词频统计。
import collections
with open(r"D:\count.txt",'r') as fp:
    list = fp.read().split()
    print(collections.Counter(list))

Counter()函数的参数必须是一个一维的,可以时数组,字典,字符串。

编写一个C语言程序来统计文本文件每个单词出现的次数,可以分为以下几个步骤: 1. 打开文件:首先需要打开指定的文本文件,通常使用`fopen()`函数。 ```c #include <stdio.h> FILE *file = fopen("filename.txt", "r"); if (file == NULL) { printf("Failed to open file.\n"); return; } ``` 2. 读取文件内容:通过`fgets()`逐行读取文件内容,并将每行分割成单词数组。 ```c char line[1000]; while (fgets(line, sizeof(line), file)) { // 分割单词 char *word = strtok(line, " "); while (word != NULL) { // 统计单词 // ... word = strtok(NULL, " "); } } ``` 3. 计数和存储:创建一个结构体或哈希表来保存每个单词及其对应的计数。这里我们可以使用`struct WordCount` 或者 `std::map<char*, int>` 来记录。 ```c #include <ctype.h> // 对于tolower() 函数 typedef struct { char* word; int count; } WordCount; WordCount word_counts[MAX_WORDS]; // 根据实际需求设置MAX_WORDS大小 int count_index = 0; // 更新计数 void update_count(char* word) { word = tolower(word); // 转换为小写便于比较 for (int i = 0; i < count_index; i++) { if (!strcmp(word, word_counts[i].word)) { word_counts[i].count++; break; } } if (i == count_index) { word_counts[count_index].word = strdup(word); word_counts[count_index].count = 1; count_index++; } } ``` 4. 关闭文件:完成所有处理后,记得关闭文件。 ```c fclose(file); ``` 5. 输出结果:遍历结构体,打印每个单词及其出现次数。 ```c for (int i = 0; i < count_index; i++) { printf("%s: %d\n", word_counts[i].word, word_counts[i].count); } ``` 完整的代码示例如下: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORDS 1000 ... void main() { // 省略打开、读取文件和更新计数部分... // 输出结果 for (int i = 0; i < count_index; i++) { printf("%s: %d\n", word_counts[i].word, word_counts[i].count); } // 省略关闭文件部分... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值