读取一个英文的文本文件,统计文本文件中的单词的词频,按照词频从大到小依次输出单词和词频

该程序读取文件并统计其中单词出现频率,忽略非字母字符并统一为小写。遇到重复单词则计数增加,最后显示每个单词及其出现次数。适用于处理含有特殊字符和大小写的文本输入。
#include <iostream>
#include <map>
#include <algorithm>
#include <fstream>
using namespace std;
void erasenotletter(string& s) {
	string::iterator it;
	it= remove_if(s.begin(), s.end(), [](char &c) {
		bool x = 0;
		if (c >= 'a' && c <= 'z') x = 1;
		else if (c >= 'A' && c <= 'Z') {
			c += 32;
			x = 1;
		}
		return !x;
		});
	while (it != s.end()) {
		s.erase(it, it + 1);
		it = remove_if(s.begin(), s.end(), [](char c) {
			bool x = 0;
			if (c >= 'a' && c <= 'z') x = 1;
			else if (c >= 'A' && c <= 'Z') x = 1;
			return !x;
			});

	}
}
class compare {
	string s;
public:
	compare(string& a) {
		s = a;
	}
	bool operator()(map<string, int>::value_type& pair) {
		return pair.first == s;
	}
};
void display(map<string,int>::value_type&pair) {
	cout << pair.first << ": " << pair.second <<  endl;
}
int main() {
	map <string, int> m;
	ifstream file_in("test1.txt", ios::in);
	string a;
	map<string, int>::iterator it;
	while (!file_in.eof()) {
		file_in >> a;
		erasenotletter(a);
		if (a.size() == 0) {
			continue;
		}
		it = find_if(m.begin(), m.end(), compare(a));
		if (it != m.end()) {
			(*it).second++;
		}
		else {

			m.insert(make_pair(a, 1));
		}
	}
	for_each(m.begin(), m.end(), display);
	
	file_in.close();
	return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值