C++单词统计(文件流、正则的应用)

来源:互联网 发布:传奇手游 源码 编辑:程序博客网 时间:2024/05/16 04:40
    //统计单词个数    ifstream ifs("file1.txt");    regex r("\\w+");    int wordCount=count_if(istream_iterator<string>(ifs),istream_iterator<string>(),[&](const string &s){return regex_search(s,r);});

统计文件中单词个数:

#include <map>     #include <fstream>     #include <iostream>     #include <string> #include <regex>using namespace std;     void display_map(map<string, int> &wmap);     /***function:统计文本中每个单词出现的次数*author: j.cai*email: jcai@mail.com*/int main(){       const char *mInputFileName="Text.txt";         ifstream ifs(mInputFileName);         string mStrTemp;         map<string, int> mCountMap;       //按行读入文件,用正则找出单词,进行统计    regex regWordPattern("[a-zA-Z]+");//单词的正则式:1)\w+:包含数字 2)[a-zA-Z]:只含字母    while (getline(ifs,mStrTemp)){//逐行读入        const std::sregex_token_iterator end;        for(sregex_token_iterator wordIter(mStrTemp.begin(),mStrTemp.end(),regWordPattern);wordIter!=end;wordIter++){//在一行文本中逐个找出单词            //cout<<*wordIter<<endl;//每个单词            mCountMap[*wordIter]++;//单词计数        }    }    display_map(mCountMap);         return 1;     }     void display_map(map<string, int> &wmap){         map<string, int>::const_iterator map_it;         for (map_it=wmap.begin(); map_it!=wmap.end();map_it++)         {             cout<<"(\""<<map_it->first<<"\","<<map_it->second<<")"<<endl;         }     } 
0 0