读取文本文件并输出单词数,不同单词和最常使用的单词

我必须从文本文件中读取所有单词并输出单词总数,不同单词数和最常用单词。 我还是初学者,所以任何帮助都很棒。

在阅读单词时,省略了连字符/撇号/标点符号,因此奥康纳与奥康纳的单词相同。 <—我不知道如何去做,所以任何帮助都会很棒。

这是我到目前为止所做的,但是现在当我尝试编译时,它给了我strcpy的警告,并说我没有正确使用它。 单词总数的输出有效,但它给出了0表示不同单词的数量,而对于最常用的单词则没有。

任何帮助都会很棒,谢谢!

 #include  #include  #include  int main(int argc, char *argv[]) { int number=0; int i; char *temp; char *temp2; char word[2500][50]; int wordCount=0; int mostFreq=1; char mostFreqWord[2500][50]; int frequentCount=0; int distinctCount=0; int j; char *p; FILE *fp; //reads file! fp= fopen("COEN12_LAB1.txt", "r"); if(fp == NULL) // checks to see if file is empty { printf("File Missing!\n"); return 0; } while(fscanf(fp,"%s", word) == 1) //scans every word in the text file wordCount++; //counts number of words while(fscanf(fp,"%s",word) == 1) { for(i=0;i<wordCount;i++) { temp=word[i]; for(j=0;jmostFreq) { strcpy(mostFreqWord,word[i]); //this doesn't work } } distinctCount++; } } } printf("Total number of words: %d\n", wordCount); printf("Total number of distinct words: %d\n", distinctCount); printf("The most frequently appeared word is: %s \n", &mostFreqWord); fclose(fp); } 

strcpy()的问题是,正如Beginner在答案中所诊断的那样,如果要复制到mostFreqWord ,则需要下标它,因为它是一个2D数组。

但是,你有一个更基本的问题。 您的单词计数循环读取直到EOF,并且您不倒回文件以重新开始。 此外,重新读取这样的文件并不是一个特别好的算法(如果你正在阅读从另一个程序输入的数据,则根本不起作用)。

你应该结合两个循环。 计算单词到达时的数量,但也要清理单词(删除非字母字符 – 或者是非字母数字字符,并且_是否为_或者数字?),然后将其插入单词列表中(如果不是已出现或增加该单词的频率计数(如果已出现)。

当输入阶段完成后,您应该准备好不同单词的数量,并且您将能够通过扫描频率列表找到最频繁的数字来找到最大值(以及出现最大值的索引号) ),然后适当报告。