【问题标题】:Program to read words from a file and count their occurrence in the file程序从文件中读取单词并计算它们在文件中的出现次数
【发布时间】:2013-03-08 16:17:11
【问题描述】:

我目前正在尝试制作一个读取文件的程序,以查找每个唯一单词并计算该单词在文件中出现的次数。我目前向用户询问一个单词并在文件中搜索该单词出现的次数。但是我需要程序自己读取文件,而不是向用户询问单个单词。

这是我目前拥有的:

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

int main(int argc, char const *argv[])
{   
int num =0;
char word[2000];
char *string;

FILE *in_file = fopen("words.txt", "r");

if (in_file == NULL)
{
    printf("Error file missing\n");
    exit(-1);
}

scanf("%s",word);

printf("%s\n", word);

while(!feof(in_file))//this loop searches the for the current word
{
    fscanf(in_file,"%s",string);
    if(!strcmp(string,word))//if match found increment num
    num++;
}
printf("we found the word %s in the file %d times\n",word,num );
return 0;
}

我只需要一些帮助来弄清楚如何读取文件中的唯一单词(尚未检查的单词),尽管对我的程序有任何其他建议将不胜感激。

【问题讨论】:

  • 你需要保存一张你见过的单词表以及你见过它们的次数。 C 没有提供这样的机制,因此您需要自己制作或使用库,但是像树或哈希表这样的东西是合适的。
  • 顺便说一句,不要像那样使用feof() - 你应该检查fscanf() 的结果(或至少首先检查)。

标签: c file


【解决方案1】:

如果您只想将文件中包含的每一行打印一次,则必须将已读取的字符串保存在给定的数据结构中。例如,排序数组可以解决问题。代码可能如下所示:

#include <stddef.h>

size_t numberOfLine = getNumberOfLine (file);
char **previousStrings = allocArray (numberOfLine, maxStringSize);
size_t i;

for (i = 0; i < numberOfLine; i++)
{
    char *currentString = readNextLine (file);

    if (!containString (previousStrings, currentString))
    {
        printString (currentString);
        insertString (previousStrings, currentString);
    }
}

您可以使用二进制搜索以有效的方式对函数containStringinsertString 进行编码。请参阅here 了解更多信息。

【讨论】:

    【解决方案2】:

    您必须将代码拆分为函数(子例程)。

    一个函数会读取文件并记录所有单词;另一个会计算每个单词的出现次数。

    int main(int argc, char const *argv[])
    {
        char *words[2000];
    
        // Read the file; store all words in the list
        int number_of_words = ReadWords("words.txt", words, 2000);
    
        // Now count and print the number of occurrences for each word
        for (int i = 0; i < number_of_words; i++)
        {
            int n = CountOccurrences(words[i], "words.txt");
            printf("we found the word %s in the file %d times\n", words[i], n);
        }
    
        // Deallocate dynamically allocated memory
        Cleanup(words, number_of_words);
    }
    

    注意main 函数相对较短。所有细节都在函数ReadWordsCountOccurrences中。

    实现从文件中读取所有单词:

    int ReadWords(const char *filename, char *words[], int max_number_of_words)
    {
        FILE *f = fopen(filename, "rt"); // checking for NULL is boring; i omit it
        int i;
        char temp[100]; // assuming the words cannot be too long
    
        for (i = 0; i < max_number_of_words; ++i)
        {
            // Read a word from the file
            if (fscanf(f, "%s", temp) != 1)
                break;
            // note: "!=1" checks for end-of-file; using feof for that is usually a bug
    
            // Allocate memory for the word, because temp is too temporary
            words[i] = strdup(temp);
        }
        fclose(f);
    
        // The result of this function is the number of words in the file
        return i;
    }
    

    【讨论】:

    • 我知道这是 3 年前的,但是 fscanf(...) != 1 和 fscanf(...) != EOF 有什么区别?
    • 与 1 比较还将检查输入中的语法错误,而不仅仅是文件结尾。在这里解释:en.cppreference.com/w/c/io/fscanf
    【解决方案3】:
    `#include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char*argv[])
    {   
    int num =0;
    char word[2000];
    char string[30];
    
    FILE *in_file = fopen(argv[1], "r");
    
    if (in_file == NULL)
    {
        printf("Error file missing\n");
        exit(-1);
    }
    
    scanf("%s",word);
    
    printf("%s\n", word);
    
    while(!feof(in_file))//this loop searches the for the current word
    {
        fscanf(in_file,"%s",string);
        if(!strcmp(string,word))//if match found increment num
        num++;
    }
    printf("we found the word %s in the file %d times\n",word,num );
    return 0;
    }`
    
    if any suggestion plz..most welcome
    
    Blockquote
    

    【讨论】:

    • 虽然这段代码可能有助于解决问题,但它并没有解释为什么和/或如何回答问题。提供这种额外的背景将显着提高其长期教育价值。请edit您的答案添加解释,包括适用的限制和假设。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多