C++词频统计程序 map容器统计单词频率(词频.统计.容器.单词.频率...)

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

c++词频统计程序 map容器统计单词频率

在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容器统计单词频率的详细内容,更多请关注知识资源分享宝库其它相关文章!

标签:  词频 统计 容器 

发表评论:

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