商城首页欢迎来到中国正版软件门户

您的位置:首页 >C++词频统计程序开发与map应用详解

C++词频统计程序开发与map应用详解

  发布于2026-02-14 阅读(0)

扫一扫,手机访问

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

怎样用C++开发词频统计程序 文本分析与map容器应用

词频统计是文本分析中的基础任务,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]++;
            }
        }
    }
}

使用 map 统计词频

std::map<std::string, int> 会自动按键(单词)排序,并且每个键唯一。当插入一个已存在的单词时,map 会更新其对应的计数。

map 的 operator[] 在键不存在时会自动创建并初始化为 0,因此可以直接使用 wordCount[word]++ 进行累加。

优点:

  • 自动去重和排序
  • 插入和查找平均时间复杂度为 O(log n)
  • 代码简洁,逻辑清晰

输出结果

遍历 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++ 能高效、清晰地完成词频统计任务。处理时注意忽略标点、统一大小写,结果会更准确。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注