用c++编程:统计一个英文文本文件中一个特定单词出现的次数,并将结果存入指定文件中!

2025-02-23 14:07:29
推荐回答(2个)
回答1:

#include
#include
using namespace std;
int main()
{
string getWord, testWord;
int n=0;//计数
cout<<"输入要查找的特定单词\n";
cin>>testWord;
ifstream infile("英文文本.txt");

while(infile>>getWord)
{
if(getWord==testWord) ++n;
}
ofstream outfile;
outfile.open("指定文件.txt"); outfile< return 0;
}

回答2:

#include   
#include   
#include   
#include        //STL中的map类

using namespace std;


//统计文本文件的词频
map statWordFrequency(string pathFileName)
{
    string wordTemp;
    map wordFrequency;

    ifstream fin(pathFileName.c_str(), ios::in);
    
    if (fin.fail())
    {
        cout<<"Open file failed!"<        exit(1);
    }
    
    while(fin>>wordTemp)
    {
        //可在此增加单词wordTemp的一些预处理,比如: 
        //统一转换成小写The->the,
        //去除标点符号 , . ! # @ " 
        //找根词 anpples->anpple, boxes->box

        wordFrequency[wordTemp]++;
    }

    fin.close();

    return wordFrequency;
}

//显示词频表
void displayWF(map & wordFrequency)
{
    map::const_iterator mIt;
    
    for (mIt=wordFrequency.begin(); mIt!=wordFrequency.end();mIt++)
    {
        cout<<"(\""<first<<"\","<second<<")"<    }
}

int main()
{
    
    string pathName = "6.5.test.txt";
    string wordQuery = "the";
    map wf;

    wf = statWordFrequency(pathName);

    
    //显示特定单词出现的次数
    cout<<"(\""<
    //显示所有单词的出现的次数
    //displayWF(wf);

    return false;
}