C语言寻找高频词
时间: 2025-04-23 08:10:26 浏览: 16
### 实现C语言中查找文本文件中的高频词
为了实现这一功能,程序会读取文本文件的内容,并通过特定算法统计其中各个单词的出现频率。下面是一个完整的解决方案。
#### 函数设计与逻辑流程
定义一个结构体`WordCount`用于存储每个唯一单词及其计数值:
```c
typedef struct WordNode {
char word[50];
int count;
struct WordNode* next;
} WordCount;
```
初始化头节点作为链表起点以便于管理不同单词的信息[^1]。
接着创建辅助函数完成基本操作,比如向列表添加新项、比较两个字符串是否相等以及释放分配内存空间等。
对于输入处理部分,考虑到实际应用环境可能较为复杂,因此采用更灵活的方式接收外部数据源——即允许用户自定义路径加载目标TXT文档;同时支持设置分隔符参数以适应多种编码习惯下的语料分析需求[^2]。
核心在于遍历整个文本流的过程中逐字解析成有意义单元(这里指代“词语”),每当遇到非字母字符时便触发一次判断:如果当前缓存区内的临时串有效,则查询其是否存在已有记录里;不存在的话新建结点加入队列末端,反之更新现有条目的数量字段值加一。
当所有内容都被扫描完毕之后,按照题目要求筛选出排名前十位的结果集输出至屏幕显示出来即可[^3]。
以下是具体代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_LENGTH 50
#define TOP_N_WORDS 10
// 定义单个词条的数据结构
typedef struct WordNode {
char word[MAX_WORD_LENGTH];
int count;
struct WordNode *next;
} WordCount;
void add_word(WordCount **head, const char *word);
int compare_words(const void *a, const void *b);
int main() {
FILE *file = fopen("example.txt", "r");
if (!file) {
perror("无法打开文件");
return EXIT_FAILURE;
}
WordCount *head = NULL;
char ch;
char current_word[MAX_WORD_LENGTH] = "";
size_t index = 0;
// 开始逐字符读入并构建哈希表
while ((ch = fgetc(file)) != EOF) {
if (isalpha(ch)) {
current_word[index++] = tolower(ch);
continue;
}
if (index > 0) {
current_word[index] = '\0';
add_word(&head, current_word);
// 清除缓冲区准备下一轮循环
memset(current_word, 0, sizeof(current_word));
index = 0;
}
}
fclose(file);
// 将链表转换为数组方便后续排序
WordCount nodes[TOP_N_WORDS], *p;
int node_count = 0;
for (p = head; p && node_count < TOP_N_WORDS; ++node_count, p=p->next){
strcpy(nodes[node_count].word , p->word );
nodes[node_count].count = p->count ;
}
qsort(nodes, node_count, sizeof(*nodes), compare_words);
printf("The most common %d words are:\n", TOP_N_WORDS);
for(int i=0 ;i<node_count;i++){
printf("%s : %d\n", nodes[i].word,nodes[i].count);
}
// 清理资源
while(head){
WordCount *temp=head;
head=temp->next;
free(temp);
}
return EXIT_SUCCESS;
}
// 向链表中增加新的单词实例
void add_word(WordCount **head_ref, const char *new_word) {
WordCount *current = *head_ref;
while (current != NULL) {
if(strcmp(new_word,current->word)==0){
current->count++;
return;
}
current=current->next;
}
WordCount *new_node=(WordCount *)malloc(sizeof(struct WordNode));
strncpy(new_node->word,new_word,strlen(new_word)+1);
new_node->count=1;
new_node->next=*head_ref;
*head_ref=new_node;
}
// 对比器函数供qsort调用
int compare_words(const void *a, const void *b) {
return (*(struct WordNode **) b)->count - (*(struct WordNode **) a)->count;
}
```
此段代码实现了从指定位置读取纯文本资料,并能够有效地识别内部含有的重复片段,最终给出按降序排列后的前N名热门词汇清单[^2].
阅读全文
相关推荐





