繁体   English   中英

读取多个文本文件并计算一个单词的出现次数?

[英]read multiple text files and count the occurances of a word?

我应该从具有多个(21578)文本文件的文件夹中读取(扫描)数据,并且文件名从1到21578编号,并读取文本文件中出现的每个单词,并计算它出现的次数。整个文件夹,即; 在所有文件中我该怎么做? 请帮助。

    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;

    void main ()
    {
    string STRING;
ifstream infile;
for(int i=0;i<21578;i++)
    {


infile.open (i+".txt");
    while(!infile.eof) // To get you all the lines.
    {
        getline(infile,STRING); // Saves the line in STRING.
        cout<<STRING; // Prints our STRING.
    }
infile.close();
system ("pause");
    }
    }

最简单的方法是创建一个字符串到整数的映射。

std::map<std::string, int>

然后增加包含int的值,如果不存在,则添加到地图。

http://www.cplusplus.com/reference/map/map/

如果您使用的是c ++ 11(我认为)或更高版本,则甚至可以使用unordered_map,它不是使用排序来访问元素而是使用散列。 如果性能很重要,则可以考虑进行此优化。

这是一些示例代码,可以帮助您入门

#include <iostream>
#include <map>
#include <string>
using namespace std;

void incrementString(map<string, int> &theMap, string &theString) {
    if(theMap.count(theString)) {
        theMap[theString]++;
    } else {
        theMap[theString] = 1;//This fixes the issue the other poster mentioned, though on most systems is not necessary, and this function would not need an if/else block at all.
    }
}

void printMap(map<string, int> &theMap) {
    map<string, int>::iterator it = theMap.begin();

    do {
        cout << it->first << ": " << it->second << endl;
    } while(++it != theMap.end());

}

int main() {
    map<string, int> stringMap;

    string hi = "hi";//Assigning "hi" to a string, like like cin>>string would.
    string the = "the";

    incrementString(stringMap, hi);//Adding one occurance of hi to the map

    incrementString(stringMap, the);//Adding one occurance of the to the map

    incrementString(stringMap, hi);//Adding another occurance of hi to the map

    printMap(stringMap); //Printing the map so far
}

int main_alt() {
    map<string, int> stringMap;

    string someString;

    while(cin>>someString) {//reads string from std::cin, I recommend using this instead of getline()
        incrementString(stringMap, someString);
    }

    printMap(stringMap);
}

因此,预期输出为:

hi: 2
the: 1

另外,如果您将“ main_alt()”设置为空,则可以这样调用程序,并查看while(cin >> string)行的工作方式。

./program < someFile.txt

读取目录中的所有文件时,最好使用操作系统功能,而不要假设文件名是什么(除非能或多或少地保证文件名)。因此,我建议在POSIX中使用opendirreaddir Windows中的兼容系统和类似设施。

现在,在计算发生次数时,您自然会以以下方式求助于std::map<string, int>

// collect

for (all files) {
    open fin;

    while (fin >> str)
        mymap[str]++;   // will create an entry if not here with a default value of 0

}

// print counts

for (map<string,int>::iterator it = m.begin(); it != m.end(); ++it)
    cout << it->first << "  :  " << it->second << std::endl;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM