#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; }
读取一个英文的文本文件,统计文本文件中的单词的词频,按照词频从大到小依次输出单词和词频
于 2022-05-17 00:17:35 首次发布
该程序读取文件并统计其中单词出现频率,忽略非字母字符并统一为小写。遇到重复单词则计数增加,最后显示每个单词及其出现次数。适用于处理含有特殊字符和大小写的文本输入。
9817

被折叠的 条评论
为什么被折叠?



