计算特定单词在c++文本文件中出现的次数

Counting how many times certain words show up in a text file in C++

本文关键字:文件 文本 单词 c++ 计算      更新时间:2023-10-16

我正试图用两个不同的文本文件制作一个程序。其中一个包含我要分析的实际文本,另一个包含单词列表。程序应该检查列表中的单词何时出现在文本中并计数。以下是我到目前为止的(不工作的)代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main () {
    string word1;
    string word2;
    int listHits = 0;
    ifstream data1 ("text.txt");
    if ( ! data1 ) {
    cout << "could not open file: " << "text.txt" << endl;
        exit ( EXIT_FAILURE );
  }
    ifstream data2 ("list.txt");
    if ( ! data2 ) {
    cout << "could not open file: " << "list.txt" << endl;
        exit ( EXIT_FAILURE );
  }
    while ( data1 >> word1 ) {
        while ( data2 >> word2 ) {
            if ( word1 == word2 ) {
                listHits++;
            }
        }
    }
    cout << "Your text had " << listHits << " words from the list " << endl;
    system("pause");
    return 0;
}

如果text.txt包含

这是一段文字。它将被加载到一个程序中。

和list.txt包含

预期结果为3。然而,无论文本文件中有什么,程序总是给我答案0。我已经检查了程序实际上是通过计算循环次数来读取文件的,并且它工作了。

Thanks in advance

在我看来,你总是只比较第一个文件的第一个字母和整个第二个文件,你做:

  while ( data1 >> word1 ) {
        while ( data2 >> word2 ) { // <---- after this ends the first time, it will never enter again
            if ( word1 == word2 ) {
                listHits++;
            }
        }

你需要在第二个循环结束后"重置"data2,这样它就会从文件的开头重新开始读取:

 while ( data1 >> word1 ) {
        while ( data2 >> word2 ) {
            if ( word1 == word2 ) {
                listHits++;
            }    
        }
        data2.seekg (0, data2.beg);
   }

程序只遍历"目标单词列表"(即data2)文件一次。文件流是"单向的":一旦耗尽,就需要倒带,否则它将留在最后。内循环

while ( data2 >> word2 )
    ...

将只执行第一次,即data1的第一个字。对于第二个和随后的所有单词,data2将已经在文件的末尾,因此代码甚至不会进入循环。

你应该在内存中读取目标单词,并在内循环中使用该列表。更好的是,将单词放在set<string>中,并使用该集合进行计数。