使用C++语言统计文件中出现频率排前10的单词

思路:

  1. 从文件中读出每一行,将字符串中的标点符号替代为空格;
  2. 使用字符串输入流将字符串里的各个单词赋给单个单词变量;
  3. 将单词和出现的次数构成映射放入map中;
  4. 排序: 复制map到vector中,重载>运算符进行排序。

代码:

#include<iostream>
#include<map>
#include<vector>
#incude<algorithm>
#include<string>
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 this->word == s;
	}
};


class CWordMap
{
private:
	map<CWord, int> wordmap;
public:
	bool AddString(string s)
	{
		map<CWord, int>::iterator it = wordmap.find(s);
		if (it == wordmap.end())
		{
			pair<CWord, int> p(CWord(s), 1);
			wordmap.insert(p);
		}
		else
		{
			(*it).second += 1;
		}

		return true;
	}

	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 << ((*it).first).GetWord() << "\t" << (*it).second << endl;
			it++;
			
		}
	}



	map<CWord, int>::iterator begin()
	{
		return wordmap.begin();
	}

	map<CWord, int>::iterator end()
	{
		return wordmap.end();
	
	}

	
};

bool compare(pair<CWord,int> &mp1, pair<CWord,int> &mp2)
{
	return mp1.second > mp2.second;
}

int  main()
{
	CWordSet wordset;
	CWordMap wordmap;
	int pos = 0;
	string s = "";
	string deliset = ",.";
	ifstream in("data.txt");
	while (!in.eof())
	{
		getline(in, s);
		if (s == "")
		{
			continue;
		}
		pos = 0;
		while ((pos = s.find_first_of(deliset,pos))!=string::npos)
		{
			s.replace(pos, 1, " ");
		}
		istringstream str(s);
		while (!str.eof())
		{
			str >> s;
			if (s == "")
				continue;
			wordmap.AddString(s);
			//wordset.AddString(s);

		}
		
	}
	in.close();
	cout<<"未排序前:"<<endl;
	wordmap.Show(cout);
	vector<pair<CWord, int>>::iterator it= v.begin();
	int n = 0;
	cout<<"排序后:"<<endl;
	while (it!= v.end())
	{
		if (n != 10)
		{
			cout << (*it).first.GetWord() << ":" << (*it).second << endl;
			it++;
			n++;
		}
		else
			break;
		
	}
	return 0;
}

程序运行截图:
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XIE_QAID

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值