1. 程式人生 > >C++實現簡單的文本查詢

C++實現簡單的文本查詢

ber number map () first begin ifstream adf times

  1 該程序將讀取用戶指定的任意文本文件,然後允許用戶從該文件中查找單詞。查詢的結果是該單詞出現的次數,並列出每次出現所在的行。如果某單詞在同一行中多次出現,程序將只顯示該行一次,行號按升序顯示。
  2 
  3 以下是代碼實現:
  4 
  5 #include <ctype.h>
  6 #include <iostream>
  7 #include <string>
  8 #include <map>
  9 #include <set>
 10 #include <vector>
 11 #include <sstream>
 12
#include <fstream> 13 #include <algorithm> 14 #include <iterator> 15 using std::cout; 16 using std::endl; 17 using std::map; 18 using std::set; 19 using std::vector; 20 using std::string; 21 using std::ifstream; 22 using std::ofstream; 23 using std::istringstream; 24 25
class Query 26 { 27 public: 28 void readFile(const string filename); 29 void query(const string & world); 30 31 private: 32 vector<string> _lines; 33 map<string,set<int>> word2line; 34 map<string,int> _wordFreq; 35
}; 36 37 void Query::readFile(const string filename) 38 { 39 ifstream ifs(filename); 40 if(!ifs.good()) 41 { 42 cout << "Oops!" << endl; 43 return; 44 } 45 string line; 46 int setnumber = 0; 47 while(getline(ifs,line)) 48 { 49 _lines.push_back(line); 50 ++setnumber; 51 istringstream iss(line); 52 string word; 53 while(iss >> word) 54 { 55 map<string,int>::iterator it = _wordFreq.begin(); 56 while(it != _wordFreq.end()) 57 { 58 if(word==it->first) 59 { 60 ++(it->second); 61 word2line[word].insert(setnumber); 62 break; 63 } 64 ++it; 65 } 66 if(it == _wordFreq.end()) 67 { 68 _wordFreq[word]=1; 69 word2line[word].insert(setnumber); 70 } 71 } 72 } 73 ifs.close(); 74 } 75 76 void Query::query(const string & word) 77 { 78 if(!_wordFreq[word]) 79 { 80 cout << "word:" << word << " --> Not found!" << endl; 81 } 82 else 83 { 84 cout << word << " occurs " << _wordFreq[word] << " times." << endl; 85 for(auto & elem : word2line[word]) 86 { 87 cout << " (line " << elem << ") " << _lines[elem-1] << endl; 88 } 89 } 90 } 91 92 int main(int argc,char *argv[]) 93 { 94 if(argc!=3) 95 { 96 cout << "Oops!" << endl; 97 return -1; 98 } 99 Query qur; 100 qur.readFile(argv[1]); 101 qur.query(argv[2]); 102 103 return 0; 104 }

C++實現簡單的文本查詢