C++ 词频统计与齐普夫定律

本文介绍了如何使用C++进行词频统计,通过Visual Studio Code预处理文本,去除非字母字符和单字母词,然后利用map进行计数。接着将map转为vector并排序,展示频率最高的单词。最后,文章讨论了齐普夫定律,并给出了Python程序绘制对数关系图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前期准备

首先使用 Visual Studio Code 输入正则表达式 [^a-zA-Z\n] 替换所有非字母(即汉语和数字等其他字符)。再用 \b[a-zA-Z]\b 除去所有单个字母组成的词(存在大量 ABCD 选项)。然后保存为 txt 格式 ( 路径不应有中文)。

编写代码

因为之前已经使用正则表达式处理过,所以这里直接读取每个单词,然后全部转换为小写字母,之后利用 map 将每一个单词计数。为了将词频由高到低输出,把 map 中元素转存到 vector 中,使用 STL 中排序算法进行排序(已经在前面定义了排序的方式)。最后将排序完成的 vector 按顺序输出。
整体代码如下:

#define LOCAL
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <algorithm>
#include <cstring>
#include <string>
#include <math.h>
#include <vector>
#include <map>
#include <bitset>
#include <sstream>
#include <map>

using namespace std;

typedef pair<string, int> PAIR;

bool cmp_by_value(const PAIR& lhs, const PAIR& rhs)
{
    
    
    return lhs.second > rhs.second;
}

struct CmpByValue
{
    
    
    bool operator()(const PAIR& lhs, const PAIR& rhs)
    {
    
    
        return lhs.second > rhs.second;<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值