← 返回教程目录
第 5 章 · 第 1 节 词频分析

基础词频:jieba + Counter 出 Top 100

Basics: jieba + Counter for Top-100

词频分析是文本分析最基础的招式,几乎所有老板的需求都从这里起步 — 这批评论里出现最多的词是什么。

核心思路:分词 → 去停用词 → 统计频次 → 排序取 Top N。4 步,5 行核心代码搞定。

1. 准备语料

import pandas as pd





# 从 CSV 读评论(也可以是 TXT、Excel)


df = pd.read_csv('comments.csv')


texts = df['content'].tolist()  # 一条评论一个 str


print(f'共 {len(texts)} 条评论')


# 共 50000 条评论

2. jieba 分词 + 去停用词

import jieba





# 停用词表(常见的/了/是等没意义的词)


stopwords = set(open('stopwords.txt', encoding='utf-8').read().splitlines())





def tokenize(text):


    words = jieba.lcut(text)  # 精确模式分词


    return [w for w in words if w.strip() and w not in stopwords and len(w) > 1]





# 批量处理


all_words = []


for text in texts:


    all_words.extend(tokenize(text))





print(f'分词后总词数: {len(all_words)}')


# 分词后总词数: 832174

3. 统计 Top 100

from collections import Counter





counter = Counter(all_words)


top100 = counter.most_common(100)





for word, count in top100[:10]:


    print(f'{word:8s} {count:6d}')


# 手机     8762


# 不错     7431


# 物流     6820


# 屏幕     6103


# 续航     5892


# 拍照     5120


# 速度     4801


# 发热     3214


# 降价     2980


# 客服     2610
实战提醒:Top 10 通常就是老板想看的核心结论。如果想更精细,加 len(w) > 1 过滤单字(比如的/了),再加自定义词典提升专业词识别。

4. 导出 Excel 给老板

import pandas as pd





df_top = pd.DataFrame(top100, columns=['词', '频次'])


df_top['占比'] = (df_top['频次'] / len(all_words) * 100).round(2)


df_top.to_excel('word_frequency_top100.xlsx', index=False)


print('已导出 word_frequency_top100.xlsx')

这 4 步的清洗 + 统计 + 导出模板,是词频分析的标配。下一节我们把它升级到指定关键词的精准统计。

想跳过写代码,直接出 Top-N 词频表 + 词云图?

配套软件内置案例数据 + 模板,导入即出图,无需写代码

查看淘宝软件 →