gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:19 25 4
gpt4 key购买 nike

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

在阅读单词时,省略了连字符/撇号/标点符号,因此 O'connor 与 Oconnor 是同一个词。 <---我不知道该怎么做,所以任何帮助都会很棒。

这是我目前所拥有的,但现在当我尝试编译时,它会通过 strcpy 向我发出警告,并说我没有正确使用它。总字数的输出有效,但不同字数的输出为 0,最常用字的输出为 0。

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

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;j<wordCount;j++)
{
temp2 = word[j];
if(strcmp(temp,temp2) == 0) //check to see if word is repeated
{
frequentCount++;
if(frequentCount>mostFreq)
{
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 所诊断的那样在他们的 answer如果您要复制到 mostFreqWord,则需要为其添加下标,因为它是一个二维数组。

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

您应该将这两个循环结合起来。计算单词到达时的数量,同时清理单词(删除非字母字符——或者是非字母数字字符,_ 下划线算不算?),然后将其插入单词列表(如果它尚未出现)或增加该单词的频率计数(如果它已经出现)。

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

关于c - 读取文本文件并输出单词数、不同单词和最常使用的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19106830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com