编程,统计用户输入的一串英文文本中各单词的出现频率。

编程,统计用户输入的一串英文文本中各单词的出现频率。注意:

(1)“, . ? !”等标点符号也作为分割单词的依据。

(2)去除of、a、an、the这些无意义词语。

(3)单词不区分大小写

按字母顺序输出单词列表及其出现次数。

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
这是一个比较典型的文本处理问题,需要进行字符串的分割和哈希表的统计。具体思路如下: 1. 打开输入文件和输出文件,读取输入文件的内容。 2. 对输入文件的内容进行分割,将每个单词存储到哈希表,并统计每个单词出现次数。 3. 对哈希表单词按照出现频率从高到低进行排序。 4. 将排序后的结果输出到指定文件。 以下是对应的 C 语言代码实现: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE 1024 #define MAX_WORD 128 #define MAX_HASH 10007 typedef struct WordNode { char* word; int count; struct WordNode* next; } WordNode; WordNode* hashTable[MAX_HASH] = { NULL }; // 哈希函数 unsigned int hash(char* str) { unsigned int hash = 0; while (*str) { hash = hash * 31 + (*str++); } return hash % MAX_HASH; } // 插入单词到哈希表 void insert(char* word) { unsigned int key = hash(word); WordNode* node = hashTable[key]; while (node != NULL) { if (strcmp(node->word, word) == 0) { node->count++; return; } node = node->next; } node = (WordNode*)malloc(sizeof(WordNode)); node->word = (char*)malloc(strlen(word) + 1); strcpy(node->word, word); node->count = 1; node->next = hashTable[key]; hashTable[key] = node; } // 释放哈希表的内存 void freeHashTable() { for (int i = 0; i < MAX_HASH; i++) { WordNode* node = hashTable[i]; while (node != NULL) { WordNode* next = node->next; free(node->word); free(node); node = next; } } } // 比较函数,用于排序 int compare(const void* a, const void* b) { WordNode* node1 = *(WordNode**)a; WordNode* node2 = *(WordNode**)b; return node2->count - node1->count; } int main() { char inputFileName[MAX_WORD], outputFileName[MAX_WORD]; printf("Input file name: "); scanf("%s", inputFileName); printf("Output file name: "); scanf("%s", outputFileName); FILE* inputFile = fopen(inputFileName, "r"); if (inputFile == NULL) { printf("Failed to open input file.\n"); return 1; } char line[MAX_LINE]; while (fgets(line, MAX_LINE, inputFile)) { char* word = strtok(line, " \t\n\r\f.,:;?!()"); while (word != NULL) { insert(word); word = strtok(NULL, " \t\n\r\f.,:;?!()"); } } fclose(inputFile); WordNode* wordList[MAX_HASH]; int count = 0; for (int i = 0; i < MAX_HASH; i++) { WordNode* node = hashTable[i]; while (node != NULL) { wordList[count++] = node; node = node->next; } } qsort(wordList, count, sizeof(WordNode*), compare); FILE* outputFile = fopen(outputFileName, "w"); if (outputFile == NULL) { printf("Failed to open output file.\n"); freeHashTable(); return 1; } for (int i = 0; i < count; i++) { fprintf(outputFile, "%s %d\n", wordList[i]->word, wordList[i]->count); } fclose(outputFile); freeHashTable(); return 0; } ``` 需要注意的是,这里使用了链表法来解决哈希冲突,同时也需要在程序结束之后释放哈希表的内存。另外,为了方便起见,这里使用了标准库的快速排序函数 qsort 来对单词按照出现频率进行排序。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值