#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <set>
#include <map>
#include <algorithm>
#include <numeric>
using namespace std;
class CWord
{
string word;
public:
CWord(string word)
{
this->word = word;
}
string GetWord()const { return word; }
bool operator<(const CWord& w) const //用于添加集合用
{
return word < w.GetWord();
}
bool operator==(const string& s)const //用于查询用
{
return word == s;
}
};
class CWordSet
{
set<CWord> wordSet; /* set是个有序的集合 使用平衡二叉树进行实现 */
public:
bool AddString(string s) //单词集合添加
{
wordSet.insert(CWord(s));
return true;
}
int size()
{
return wordSet.size();
}
void Show(ostream& os) //单词集合显示
{
set<CWord>::iterator it = wordSet.begin();
int n = 0;
while (it != wordSet.end())
{
os << (*it).GetWord() << "\t";
n++;
if (n % 8 == 0)
{
os << endl;
n = 0;
}
it++;
}
}
};
class CWordMap
{
map<CWord, int> wordMap; //<单词,出现次数>
public:
bool AddString(string s)
{
map<CWord, int>::iterator it = wordMap.find(s);
if (it == wordMap.end())/* no such word in map */
{
pair<CWord, int> p(CWord(s), 1);
wordMap.insert(p);
}
else
{
(*it).second += 1;
}
return true;
}
int size()const
{
return wordMap.size();
}
void Show(ostream& os) //输出函数
{
map<CWord, int>::iterator it = wordMap.begin();
while (it != wordMap.end())
{
string ss = ((*it).first).GetWord();
int n = (*it).second;
os << ss << "\t" << n << endl;;
it++;
}
}
};
/*
* 读取一篇英文文本文件,统计单词及该单词在文件中出现的次数。
* 在使用STL进行开发后,set, map的功能使得逻辑功能更加清晰。
* 对文本文件和字符串的操作就更加重要了。
* 统计结果保存在当前文件夹下的output.txt文件中
*/
class WordCount
{
public:
WordCount(string filename) :filename(filename)
{
}
int count()
{
ifstream in(filename);
ofstream out("output.txt");
string delimset = ",./?\"\"";//待拆分字符集合delimset
while (!in.eof())
{
string s;
int pos = 0;
getline(in, s);
if ("" == s)
continue;
while ((pos = s.find_first_of(delimset, pos)) != string::npos)
s.replace(pos,1," ");
istringstream ss(s);
while (!ss.eof())
{
ss >> s; /* 空格作为分隔符号 为什么空格会被吃进去?*/
if (" " == s) /* 避免空格被吃入 */
continue;
wordset.AddString(s); /* 可以删除 */
wordmap.AddString(s);
}
}
wordmap.Show(out);
out << endl << "总单词数目:" << wordmap.size();
return 0;
}
private:
string filename;
CWordMap wordmap;
CWordSet wordset;
};
void main()
{
WordCount wcount("Interview with God.txt");
wcount.count();
}
STL统计英文中单词出现频率的问题
最新推荐文章于 2018-08-07 19:25:41 发布