简单文本查询程序

 

#include<iostream>

#include<fstream>

#include<vector>

#include<string>

#include<set>

#include<map>

#include<sstream>

 

using namespace std;

 

//功能实现:

//输入要查找的文件名和要查找的单词,显示该单词在文件中每一行出现的次数,行号按升序排列

//文本查询类

class TextQuery

{

private:

       string filename; //文件名

       fstream file;

       vector<string>filecopy; //用于存放文件,文件每一行放入filecopy对应的元素中

       map<int,int>rowcnt; //关键字是行号,关联值是出现次数

       bool Query(string word); //查询函数,给定单词word,查找它在每一行出现的次数

public:

       TextQuery(string name);

       void Query_result(string word); //显示查询的结果

};

 

TextQuery::TextQuery(string name)

{

       this->file.open(name.c_str());

       if(!this->file)

       {

              cerr<<"文件不存在!"<<endl;

              return;

       }

       this->filename=name;

       string line;

       while(getline(this->file,line))

       {

              this->filecopy.push_back(line); //将文件每一行加入到filecopy中

       }

}

 

bool TextQuery::Query(string word)

{

       vector<string>::const_iterator it;

       bool occur=false; //表示在filecopy中是否出现要查询的单词

       for(it=filecopy.begin();it!=filecopy.end();it++)

       {

              stringstream ss(*it); //ss用于将句子分解为单词

              int row=it-filecopy.begin(); //行号

              string str; //str存放copyfile每一行的单词

              int cnt=0; //word在该行中出现的次数

              while(ss>>str)

              {

                     if(word==str) //在该行出现了要查找的单词

                     {

                            cnt++;

                            occur=true;

                     }

              }

              if(cnt) rowcnt.insert(make_pair(row,cnt));

       }

       return occur;

}

 

void TextQuery::Query_result(string word)

{

       if(Query(word)==false)

       {

              cerr<<word<<"没有出现在文件中"<<endl;

              return;

       }

       map<int,int>::const_iterator it;

       for(it=rowcnt.begin();it!=rowcnt.end();it++)

       {

              cout<<"Line"<<it->first<<" "<<it->second<<"次"<<": "<<filecopy[it->first]<<endl;

       }

}

 

void main()

{

       string filename;

       cout<<"请输入要查询的文件名:";

       cin>>filename;

       TextQuery textquery(filename);

       string word;

       cout<<"请输入要查询的单词:";

       cin>>word;

       textquery.Query_result(word);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值