前期准备
首先使用 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;<