STL统计英文中单词出现频率的问题

#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();

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值