Python collections.Counter实现词频统计与Top-K查询
统计文本中单词出现的频率(词频统计)并找出出现次数最多的前几个词(Top-K查询),是数据处理和自然语言处理中的基础任务。Python 标准库中的 collections 模块提供了一个强大的工具 Counter,能够以极少的代码量高效完成这些工作。
传统方法与 Counter 的对比
在深入代码之前,先对比一下使用普通字典和使用 Counter 的区别,了解为何要选择后者。
| 实现方式 | 代码复杂度 | 执行效率 | 功能丰富度 |
|---|---|---|---|
普通 dict 循环 |
高(需手动处理键是否存在) | 一般 | 仅基础计数 |
collections.Counter |
低(一行代码搞定) | 高(C语言底层优化) | 高(含Top-K、算术运算等) |
基础操作:快速入门
导入 Counter 类并创建计数对象。
- 打开 Python 编辑器或终端。
- 输入 以下代码导入所需模块:
from collections import Counter
- 准备 一个包含可哈希元素(如字符串、数字)的列表。这里以单词列表为例:
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
- 实例化
Counter对象,传入 列表:
word_counts = Counter(words)
- 打印 结果,查看每个单词的频次:
print(word_counts)
输出结果会显示一个类似字典的结构:
Counter({'apple': 3, 'banana': 2, 'orange': 1})
进阶应用:文本清洗与词频统计
实际场景中,数据通常是原始的长字符串,包含标点符号和大小写差异,不能直接统计。需要先进行数据清洗。
处理 原始文本的清洗逻辑如下:
- 定义 一个原始文本变量:
text = "Hello world! Hello Python. Hello, world. Python is great."
-
转换 文本为小写,确保 "Hello" 和 "hello" 被视为同一个词。调用
.lower()方法。 -
移除 标点符号。使用
str.replace或正则表达式。为了简单直观,这里使用replace替换 常见标点:
# 将标点替换为空格
clean_text = text.replace('!', ' ').replace(',', ' ').replace('.', ' ')
- 分割 字符串为单词列表。使用
.split()方法:
words_list = clean_text.split()
- 传入 列表给
Counter进行统计:
counts = Counter(words_list)
print(counts)
此时输出:
Counter({'hello': 3, 'world': 2, 'python': 2, 'is': 1, 'great': 1})
核心功能:Top-K 查询
Counter 最强大的功能之一是 most_common() 方法,它能直接返回出现频率最高的前 N 个元素。
- 获取 频率最高的前 2 个单词。调用
most_common(2):
top_2 = counts.most_common(2)
print(top_2)
- 观察 输出结果。它返回一个包含元组的列表,每个元组格式为
(元素, 计数):
[('hello', 3), ('world', 2)]
- 遍历 结果以更友好的方式展示:
for word, count in top_2:
print(f"单词: {word}, 出现次数: {count}")
高级技巧:更新与算术运算
在流式数据或对比不同数据集时,Counter 提供了便利的更新和算术功能。
1. 更新计数
当有新数据到来时,使用 update() 方法增加计数,而不是覆盖原对象。
new_words = ['python', 'java', 'python']
counts.update(new_words)
# 此时 python 的计数会自动增加
2. 计数器算术
可以直接对两个 Counter 对象进行加法或减法运算。
other_counts = Counter(['java', 'c++', 'java'])
# 相加:两个集合的频率合并
total_counts = counts + other_counts
# 相减:减去对应元素的频率(结果会忽略负数和零)
diff_counts = counts - other_counts
完整代码示例
将上述步骤整合为一个完整的可运行脚本。
from collections import Counter
def analyze_text_frequency(text, top_k=None):
# 1. 数据清洗:转小写
text = text.lower()
# 2. 数据清洗:替换标点符号
for char in [',', '.', '!', '?', ';', ':']:
text = text.replace(char, ' ')
# 3. 分割
words = text.split()
# 4. 统计
counter = Counter(words)
# 5. 返回 Top-K 结果
if top_k:
return counter.most_common(top_k)
return counter
# 测试数据
sample_text = """
Python is great. Python is easy.
Java is also great. Python, Java, and C++ are popular.
"""
# 执行分析
result = analyze_text_frequency(sample_text, top_k=3)
# 输出结果
print("Top 3 Words:")
for word, count in result:
print(f"{word}: {count}")
该脚本首先对文本进行标准化处理,然后利用 Counter 计算词频,最后提取并打印出现次数最多的前 3 个单词。

暂无评论,快来抢沙发吧!