使用map统计单词频率时,程序读取文本并逐词处理,通过cleanWord和toLower函数去除标点并转为小写,以std::map<std::string, int>存储单词及出现次数,利用其自动排序特性输出有序结果,支持扩展如频率排序或文件输入。

在C++中,使用
map
std::map
程序读取输入的文本(从标准输入或文件),逐个提取单词,然后以单词为键,出现次数为值,存入
std::map<std::string, int>
#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"被统计为两个不同单词。
立即学习“C++免费学习笔记(深入)”;
标点符号处理:通过
cleanWord
输入控制:程序以空行结束输入,适合交互式使用。如需从文件读取,可将
std::cin
std::ifstream
可以添加功能如:限制只统计长度大于2的单词、输出频率最高的前N个单词、将结果写入文件等。也可以使用
vector
sort
基本上就这些,不复杂但容易忽略细节。掌握这个结构后,可以灵活应用到其他统计任务中。
以上就是C++词频统计程序 map容器统计单词频率的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号