概述
此程序可以用于查询一个英语文本中某个单词出现的次数和显示所在行数
#include<iostream>
#include<istream>
#include<fstream>
#include<ostream>
#include<string>
#include<list>
#include<vector>
#include<array>
#include<deque>
#include<algorithm>
#include<iterator>
#include<map>
#include<utility>
#include<set>
#include<memory>
#include<sstream>
using namespace std;
using namespace placeholders;
using line_no = vector<string>::size_type;
class Queryresult;
class Textquery{
public:
Textquery(ifstream&);
Queryresult query(const string&) const;
private:
shared_ptr<vector<string>> file;
map<string,shared_ptr<set<line_no>>> wm;
};
Textquery::Textquery(ifstream &is):file(new vector<string>)
{
string text;
while(getline(is,text))
{
file->push_back(text);
int n = file->size() - 1;
istringstream line(text);
string word;
while(line >> word)
{
auto &lines = wm[word];
if (!lines)
lines.reset(new set<line_no>);
lines->insert(n);
}
}
}
class Queryresult{
friend ostream& print(ostream&, const Queryresult&);
public:
Queryresult(string s,shared_ptr<set<line_no>> p, shared_ptr<vector<string>> f):
sougth(s),lines(p),file(f){}
private:
string sougth;
shared_ptr<set<line_no>> lines;
shared_ptr<vector<string>> file;
};
Queryresult Textquery::query(const string &sougth) const
{
static shared_ptr<set<line_no>> nodata(new set<line_no>);
auto loc = wm.find(sougth);
if (loc == wm.end())
return Queryresult(sougth, nodata, file);
else
return Queryresult(sougth, loc->second, file);
}
string make_plural(size_t ctr, const string &word, const string &ending)
{
return (ctr > 1) ? word + ending : word;
}
ostream &print(ostream & os, const Queryresult &qr)
{
os << qr.sougth << "occurs" << qr.lines->size() << " " << make_plural(qr.lines->size(),"time","s") << endl;
for(auto num:*qr.lines)
os << "t(line" << num + 1 << ")" << *(qr.file->begin() + num) << endl;
return os;
}
void runQueries(ifstream &infile)
{
Textquery tp(infile);
while(true)
{
cout << "enter word to look for , or q to quit:";
string s;
if (!(cin >> s) || s == "q")
break;
print(cout,tp.query(s)) << endl;
}
}
int main()
{
ifstream infile;
infile.open("text1.txt");
runQueries(infile);
return 0;
}
样例文本
George Osborne is preparing a campaign to
become the next head of the International Monetary Fund. The former chancellor has told
friends that he is considering a bid to replace Christine Lagarde and become the fund’s first British managing
director in Washington. The IMF, jointly governed by 189 countries, was set…
运行结果
最后
以上就是落寞学姐为你收集整理的C++实现文本查询程序的全部内容,希望文章能够帮你解决C++实现文本查询程序所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复