我正在尝试编写一个程序,该程序打开一个文本文件,从文件中读取,将大写更改为小写,然后计算该单词在文件中出现的次数并将结果打印到新的文本文件中.
到目前为止我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
int main()
{
FILE *fileIN;
FILE *fileOUT;
char str[255];
char c;
int i = 0;
fileIN = fopen ("input.txt", "r");
fileOUT = fopen ("output.txt", "w");
if (fileIN == NULL || fileOUT == NULL)
{
printf("Error opening files\n");
}
else
{
while(! feof(fileIN)) //reading and writing loop
{
fscanf(fileIN, "%s", str); //reading file
i = 0;
c = str[i];
if (isupper(c)) //changing any upper case to lower case
{
c =(tolower(c));
str[i] = putchar(c);
}
printf("%s ", str); //printing output
fprintf(fileOUT, "%s\n", str); //printing into file
}
fclose(fileIN);
fclose(fileOUT);
}
getch();
}
input.txt 文件包含以下内容“西类牙的雨主要落在飞机上” 别问为什么。 程序运行后,输出将如下所示: 这 雨 在 西类牙 下降 主要是 在 这 飞机
我已经成功地将大写单词小写了。我现在无法理解如何计算每个单词的出现次数。例如,在输出中,我希望它说“the 2”,意思是 2 已经出现,这也意味着我不希望在该文件中存储更多“the”。
我正在考虑 strcmp 和 strcpy,但不确定如何按照我想要的方式使用它们。
非常感谢您的帮助
(如果格式错误,抱歉)
最佳答案
您可能想要创建一个哈希表,其中单词作为键,频率作为值。
草图想法:
- 识别单词,即用空格分隔的字母数字字符串,请尝试使用 strtok()
- 对于每个单词
- 在基于哈希表的字典中搜索单词
- 如果找到:增加频率
- 如果未找到:在字典中插入一个新条目作为 (word, 1)
- 在基于哈希表的字典中搜索单词
最后,打印字典的内容,即对于所有条目,entry.word
和 entry.Frequency
有关详细信息,请参阅此问题和答案:Quick Way to Implement Dictionary in C它基于圣经《C 编程语言》第 6.6 节
根据OP的评论进行更新:
哈希表只是一个高效的表,如果你不想使用它,你仍然可以使用普通表。这里有一些想法。
typedef struct WordFreq {
char word[ N ];
int freq;
} WordFreq;
WordFreq wordFreqTable[ T ];
(N is the maximum length of a single word, T is the maximum number of unique words)
对于搜索和插入,可以在表中进行线性搜索for( int i = 0; i != T;++i ) {
关于c - 在C中对文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15823574/