用c++编程:统计一个英文文本文件中一个特定单词出现的次数,并将结果存入指定文件中!
2个回答
展开全部
#include <iostream>
#include <fstream>
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<<n;
return 0;
}
#include <fstream>
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<<n;
return 0;
}
展开全部
#include <iostream>
#include <fstream>
#include <string>
#include <map> //STL中的map类
using namespace std;
//统计文本文件的词频
map<string, int> statWordFrequency(string pathFileName)
{
string wordTemp;
map<string, int> wordFrequency;
ifstream fin(pathFileName.c_str(), ios::in);
if (fin.fail())
{
cout<<"Open file failed!"<<endl;
exit(1);
}
while(fin>>wordTemp)
{
//可在此增加单词wordTemp的一些预处理,比如:
//统一转换成小写The->the,
//去除标点符号 , . ! # @ "
//找根词 anpples->anpple, boxes->box
wordFrequency[wordTemp]++;
}
fin.close();
return wordFrequency;
}
//显示词频表
void displayWF(map<string, int> & wordFrequency)
{
map<string, int>::const_iterator mIt;
for (mIt=wordFrequency.begin(); mIt!=wordFrequency.end();mIt++)
{
cout<<"(\""<<mIt->first<<"\","<<mIt->second<<")"<<endl;
}
}
int main()
{
string pathName = "6.5.test.txt";
string wordQuery = "the";
map<string, int> wf;
wf = statWordFrequency(pathName);
//显示特定单词出现的次数
cout<<"(\""<<wordQuery<<"\","<<wf[wordQuery]<<")"<<endl;
//显示所有单词的出现的次数
//displayWF(wf);
return false;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询