答案:C++利用map容器实现词频统计,通过stringstream分割单词,normalize函数统一大小写并去除标点,processText读取文本并统计,wordCount自动计数,最后printResults输出结果。

词频统计是文本分析中的基础任务,C++ 提供了强大的标准库支持,特别是 map 容器,非常适合用来统计每个单词出现的次数。下面介绍如何用 C++ 实现一个简单的词频统计程序。
程序的第一步是读取输入文本。可以从文件读取,也可以从标准输入获取。使用 std::stringstream 可以方便地按空格分割单词。
示例代码:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <cctype>
std::map<std::string, int> wordCount;
std::string normalize(const std::string& word) {
std::string cleaned;
for (char c : word) {
if (std::isalpha(c)) {
cleaned += std::tolower(c);
}
}
return cleaned;
}
void processText(std::istream& in) {
std::string line;
while (std::getline(in, line)) {
std::stringstream ss(line);
std::string word;
while (ss >> word) {
std::string cleaned = normalize(word);
if (!cleaned.empty()) {
wordCount[cleaned]++;
}
}
}
}
std::map<std::string, int> 会自动按键(单词)排序,并且每个键唯一。当插入一个已存在的单词时,map 会更新其对应的计数。
立即学习“C++免费学习笔记(深入)”;
map 的 operator[] 在键不存在时会自动创建并初始化为 0,因此可以直接使用 wordCount[word]++ 进行累加。
优点:
遍历 map 并输出每个单词及其出现次数:
void printResults() {
for (const auto& pair : wordCount) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
}
如果想按频率从高到低排序,可以把 map 内容导入 vector,然后按值排序。
主函数中可以选择从文件或标准输入读取:
int main() {
std::ifstream file("input.txt");
if (file.is_open()) {
processText(file);
file.close();
} else {
std::cout << "无法打开文件,使用标准输入:" << std::endl;
processText(std::cin);
}
printResults();
return 0;
}
基本上就这些。通过 map 容器,C++ 能高效、清晰地完成词频统计任务。处理时注意忽略标点、统一大小写,结果会更准确。
以上就是怎样用C++开发词频统计程序 文本分析与map容器应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号