Python实现词频统计的多种方法详解

夏知夏
夏知夏
发布时间:2026-10-13| 5人浏览过
原创

本文介绍Python中统计词频的多种实现方式,涵盖基础字典遍历、get/setdefault方法、defaultdict以及Counter类。重点解析Counter的高级用法,如most_common获取高频词,帮助开发者根据场景选择最简洁高效的方案。

Python词频统计概述

Python的设计哲学倡导以极简的代码解决复杂问题。在词频统计这一常见任务中,存在多种代码实现路径。由于词频统计在数据统计、数据挖掘及分类处理中应用广泛,本文对此进行简要梳理与记录。

以下示例数据用于演示统计过程:

基础字典统计法


document = [
  'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
 'my', 'eyes', "you're", 'under']

方法一:利用原生字典进行统计(遍历加循环)。

传统遍历与条件判断


word_count = {}
for word in document:
  if word in word_count:
    word_count[word] += 1
 else:
    word_count[word] = 1

方法二:更优雅的字典操作实现。

利用get与setdefault优化


#假如字典中不存在给定的键,则返回参数中提供的默认值;反之,则返回字典中保存的值。
for word in document:
  previous_count = word_count.get(word, 0)
  word_count[word] = previous_count + 1
#可以合并成一行
for word in document:
 word_count[word] = word_count.setdefault(word, 0) + 1

方法三:使用defaultdict实现自动默认值设置。

使用defaultdict简化代码


# 使用collections中的defalutdict来实现,defalutdict是一种值可以默认设置的dict
from collections import defaultdict
word_count = defaultdict(int)
for word in document:
  word_count[word] += 1

方法四:使用Counter计数器类。

使用Counter进行高效统计


word_counter = Counter(document)

作为计数器,Counter内置了丰富的统计功能。例如,通过排序获取前n个最高频的词汇是常见需求。

获取高频词Top N


# 返回前n个最高词频,以字典的形式
word_counter.most_common(n)

对比可见,使用defaultdict和Counter的代码最为简洁,也更契合Python的开发理念。

以上内容为本文全部要点,希望能为读者提供学习参考,欢迎继续支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。