C++ 统计英文文本单词数量和出现次数
C++ 统计英文文本单词数量和出现次数
本文提供 C++ 代码实现统计英文文本中的单词数量,并统计每个单词出现的次数,包含基本版和进阶版两种实现。
输入说明 若干行英文,最后以'!!!!!'为结束。
输出说明
- 单词数量
- 出现次数排名前 10 的单词(次数按照降序排序,如果次数相同,则按照键值的字母升序排序)及出现次数。
基本版
统计时,区分字母大小写,且不删除指定标点符号。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
string line;
map<string, int> word_cnt;
while (getline(cin, line)) {
if (line.empty()) continue; // 忽略空行或空格行
int start = 0, end = 0;
while (end < line.length()) {
while (end < line.length() && line[end] == ' ') end++; // 跳过空格
start = end;
while (end < line.length() && line[end] != ' ') end++; // 找到单词结尾
if (start < end) { // 找到了一个单词
string word = line.substr(start, end - start);
word_cnt[word]++;
}
}
}
cout << "单词数量:" << word_cnt.size() << endl;
return 0;
}
进阶版
统计前,需要从文字中删除指定标点符号'!.,:*?'。 注意:所谓的删除,就是用 1 个空格替换掉相应字符。 统计单词时需要忽略单词的大小写。
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
void remove_punct(string& s) { // 删除标点
string punct = "!.,:*?";
for (char& c : s) {
if (punct.find(c) != string::npos) c = ' ';
}
}
void to_lower(string& s) { // 转换为小写
for (char& c : s) {
if (c >= 'A' && c <= 'Z') c += ('a' - 'A');
}
}
int main() {
string line;
map<string, int> word_cnt;
while (getline(cin, line)) {
if (line.empty()) continue; // 忽略空行或空格行
remove_punct(line); // 删除标点
int start = 0, end = 0;
while (end < line.length()) {
while (end < line.length() && line[end] == ' ') end++; // 跳过空格
start = end;
while (end < line.length() && line[end] != ' ') end++; // 找到单词结尾
if (start < end) { // 找到了一个单词
string word = line.substr(start, end - start);
to_lower(word); // 转换为小写
word_cnt[word]++;
}
}
}
cout << "单词数量:" << word_cnt.size() << endl;
// 按照出现次数排序
vector<pair<string, int>> word_vec(word_cnt.begin(), word_cnt.end());
sort(word_vec.begin(), word_vec.end(),
[](const pair<string, int>& a, const pair<string, int>& b) {
return a.second > b.second || (a.second == b.second && a.first < b.first);
});
// 输出前 10 个出现次数最多的单词
cout << "出现次数排名前 10 的单词及出现次数:" << endl;
for (int i = 0; i < min(10, (int)word_vec.size()); i++) {
cout << word_vec[i].first << " " << word_vec[i].second << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/oelR 著作权归作者所有。请勿转载和采集!