FreqDist 是 NLTK (Natural Language Toolkit) 库中的一个核心类,用于计算文本中各个元素(如单词、字符等)的出现频率,它是一个“频率分布”的实现,非常方便进行文本分析的基础统计。

什么是 FreqDist?
FreqDist 是一个字典的子类,专门用于存储每个样本(sample)的频率(frequency),当你给它一段文本或一个词语列表时,它会自动统计每个词语出现的次数,并方便地进行各种频率相关的分析。
它的作用就是:数数。
如何使用 FreqDist(基本步骤)
使用 FreqDist 非常简单,主要分为三步:安装 NLTK、导入、创建和使用。
步骤 1: 安装 NLTK
如果你还没有安装 NLTK,可以通过 pip 安装:

pip install nltk
步骤 2: 导入 FreqDist
在 Python 代码中,你需要从 nltk 导入 FreqDist 类。
from nltk import FreqDist
步骤 3: 创建 FreqDist 对象
你需要一个词语列表(通常是字符串列表)作为输入来创建 FreqDist 对象,这个列表通常是通过“分词”(Tokenization)得到的。
# 示例文本 text = "hello world hello python world nlp" # 分词(将句子分割成单词列表) words = text.split() # 创建 FreqDist 对象 fdist = FreqDist(words) print(fdist)
输出:
<FreqDist with 4 samples and 5 outcomes>
这个输出告诉我们,这个频率分布包含 4 个不同的样本(hello, world, python, nlp),总共出现了 5 次(hello 2次, world 2次, python 1次, nlp 1次)。

FreqDist 的常用方法和属性
创建 FreqDist 对象后,你可以使用它提供的丰富方法来进行各种分析。
1 查看频率
-
fdist[key]: 获取特定key的频率。print(fdist['hello']) # 输出: 2 print(fdist['python']) # 输出: 1 print(fdist['java']) # 输出: 0 (如果键不存在,返回0)
-
fdist.N(): 获取所有样本的总出现次数(outcomes)。print(fdist.N()) # 输出: 5
-
fdist.B(): 获取不同样本的数量(samples的基数)。print(fdist.B()) # 输出: 4
2 获取最频繁的样本
这是 FreqDist 最常用的功能之一。
-
fdist.most_common(n): 返回频率最高的n个样本及其频率的列表,按频率降序排列。# 获取频率最高的2个词 print(fdist.most_common(2)) # 输出: [('hello', 2), ('world', 2)] -
fdist.max(): 返回频率最高的单个样本。print(fdist.max()) # 输出: 'hello' (或 'world',因为两者频率相同)
3 绘制频率分布图
FreqDist 内置了绘图功能,非常直观。
-
fdist.plot(n, cumulative=False):n: 绘制频率最高的n个样本。cumulative: 如果为True,则绘制累积频率图。
import matplotlib.pyplot as plt # 绘制频率最高的3个词的频率分布图 fdist.plot(3, cumulative=False) plt.show() # 显示图像 # 绘制累积频率图 fdist.plot(3, cumulative=True) plt.show()
4 其他有用方法
-
fdist.hapaxes(): 返回只出现过一次的样本列表(“单例词”)。print(fdist.hapaxes()) # 输出: ['python', 'nlp']
-
fdist.freq(sample): 返回某个样本的频率(次数 / 总次数)。print(fdist.freq('hello')) # 输出: 0.4 (因为 2 / 5 = 0.4) -
fdist.keys(): 返回所有样本的键。print(list(fdist.keys())) # 输出: ['hello', 'world', 'python', 'nlp']
完整示例
下面是一个结合了分词、停用词过滤和 FreqDist 的完整示例,这是 NLP 中的常见流程。
import nltk
from nltk import FreqDist
from nltk.corpus import stopwords
# 下载 NLTK 的停用词数据(只需下载一次)
# nltk.download('stopwords')
# 示例文本
text = """
Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence
concerned with the interactions between computers and human language. It focuses on how to program computers
to process and analyze large amounts of natural language data. The result is a computer capable of understanding
the contents of documents, including the contextual nuances of the language within them. The technology can then
accurately extract information and insights contained in the documents as well as categorize and organize the
documents themselves.
"""
# 1. 分词
# 使用 nltk.word_tokenize 进行更智能的分词,可以处理标点符号
words = nltk.word_tokenize(text.lower()) # 转为小写,使 "The" 和 "the" 视为同一个词
# 2. 去除停用词和标点符号
stop_words = set(stopwords.words('english')) # 获取英文停用词列表
# 去除停用词和非字母字符
words = [word for word in words if word.isalpha() and word not in stop_words]
# 3. 创建 FreqDist 对象
fdist = FreqDist(words)
# 4. 进行分析
print(f"总词数: {fdist.N()}")
print(f"不同词数: {fdist.B()}")
print("\n频率最高的10个词:")
print(fdist.most_common(10))
print("\n只出现过一次的词(前10个):")
print(fdist.hapaxes()[:10])
# 5. 可视化
print("\n绘制频率最高的15个词的分布图...")
fdist.plot(15, title='Top 15 Most Common Words')
FreqDist 与 collections.Counter 的比较
在 Python 标准库中,collections.Counter 是 FreqDist 的一个轻量级替代品,功能非常相似。
| 特性 | nltk.FreqDist |
collections.Counter |
|---|---|---|
| 来源 | NLTK 库 | Python 标准库 (collections) |
| 安装 | pip install nltk |
无需安装,开箱即用 |
| 主要功能 | 频率分布、绘图、NLP相关方法 | 计数器,类似字典 |
| 绘图 | 支持 (plot(), tabulate()) |
不支持 |
| NLP集成 | 高,与 nltk 其他模块无缝集成 |
无,是通用工具 |
| 性能 | 对于非常大的语料库,可能稍慢 | 性能通常更高,是纯 Python 实现 |
- 如果你正在进行自然语言处理任务,并且需要绘图或与其他 NLTK 工具配合使用,
FreqDist是更好的选择。 - 如果你只是需要一个简单的计数工具,不关心 NLP 生态和绘图,
Counter更轻量、更高效。
使用 Counter 的例子:
from collections import Counter
text = "hello world hello python world nlp"
words = text.split()
# 使用 Counter
word_counts = Counter(words)
print(word_counts)
# 输出: Counter({'hello': 2, 'world': 2, 'python': 1, 'nlp': 1})
print(word_counts.most_common(2))
# 输出: [('hello', 2), ('world', 2)]
希望这个详细的解释能帮助你全面理解和使用 Python 中的 FreqDist 函数!
