
在C++中,使用
map容器统计单词频率是一种常见且高效的方法。通过
std::map,我们可以自动对单词进行排序,并方便地维护每个单词出现的次数。 基本思路
程序读取输入的文本(从标准输入或文件),逐个提取单词,然后以单词为键,出现次数为值,存入
std::map<std::string, int>中。每次遇到一个单词,就将其对应值加1。 完整示例代码
#include <iostream>
#include <map>
#include <string>
#include <sstream>
#include <cctype>
// 将单词转为小写,避免大小写敏感
std::string toLower(const std::string& word) {
std::string lower;
for (char c : word) {
lower += std::tolower(c);
}
return lower;
}
// 提取纯字母组成的单词,去除标点
std::string cleanWord(const std::string& word) {
std::string cleaned;
for (char c : word) {
if (std::isalpha(c)) {
cleaned += c;
}
}
return cleaned;
}
int main() {
std::map<std::string, int> wordCount;
std::string line;
std::cout << "请输入文本(输入空行结束):\n";
while (std::getline(std::cin, line) && !line.empty()) {
std::stringstream ss(line);
std::string word;
while (ss >> word) {
word = cleanWord(word);
if (!word.empty()) {
word = toLower(word);
++wordCount[word];
}
}
}
// 输出结果
std::cout << "\n单词频率统计结果:\n";
for (const auto& pair : wordCount) {
std::cout << pair.first << ": " << pair.second << '\n';
}
return 0;
}
关键点说明
map自动排序:map会按键的字典序自动排序,输出时单词是有序的。如果不需要排序,可改用
std::unordered_map提高性能。
大小写处理:将所有单词转为小写,避免"He"和"he"被统计为两个不同单词。
标点符号处理:通过
cleanWord函数过滤掉逗号、句号等非字母字符。
输入控制:程序以空行结束输入,适合交互式使用。如需从文件读取,可将
std::cin替换为
std::ifstream对象。 扩展建议
可以添加功能如:限制只统计长度大于2的单词、输出频率最高的前N个单词、将结果写入文件等。也可以使用
vector配合
sort按频率排序输出。
基本上就这些,不复杂但容易忽略细节。掌握这个结构后,可以灵活应用到其他统计任务中。
以上就是C++词频统计程序 map容器统计单词频率的详细内容,更多请关注知识资源分享宝库其它相关文章!







发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。