齐普夫定律(Zipf’s Law) 是一种经验法则,描述了 单词频率分布 在自然语言中的规律。它指出,在一篇文本或一个语料库中,单词的出现频率 f f f 与其频率排名 r r r 之间存在如下关系:
f ∝ 1 r s f \propto \frac{1}{r^s} f∝rs1
其中:
换句话说,在大多数语言中,第 r r r 频繁的单词的出现次数,大约是第 r + 1 r+1 r+1 频繁单词的 2 倍,是第 r + 2 r+2 r+2 频繁单词的 3 倍,以此类推。
对 Zipf’s Law 进行对数变换:
log f = log C − s log r \log f = \log C - s \log r logf=logC−slogr
假设在一个英语文本中,最常见的单词是 “the”,它的出现频率是 10%,那么:
示例词频排名(英语文本):
排名 r r r | 词 | 词频 f f f |
---|---|---|
1 | the | 10.0% |
2 | of | 5.0% |
3 | and | 3.3% |
4 | to | 2.5% |
5 | a | 2.0% |
… | … | … |
齐普夫定律广泛应用于:
自然语言处理(NLP)
信息检索与搜索引擎
文本压缩
社会学 & 经济学
我们可以使用 Python 统计一个文本的单词频率,并绘制 Zipf’s Law 的分布曲线。
import re
from collections import Counter
import matplotlib.pyplot as plt
import numpy as np
# 示例文本
text = """
Zipf’s law states that the frequency of a word is inversely proportional to its rank.
The most common words appear very frequently, while rare words appear infrequently.
This pattern holds in many natural languages.
"""
# 预处理文本:转换为小写 & 去除标点符号
text = text.lower()
text = re.sub(r'[^\w\s]', '', text)
# 统计单词频率
words = text.split()
word_counts = Counter(words)
# 按照频率排序
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 打印前 10 个高频单词
print("Top 10 frequent words:")
for i, (word, freq) in enumerate(sorted_word_counts[:10]):
print(f"{i+1}. {word}: {freq}")
# 提取排名和频率
ranks = np.arange(1, len(sorted_word_counts) + 1) # 词频排名
frequencies = [freq for word, freq in sorted_word_counts]
# 绘制词频分布
plt.figure(figsize=(8, 5))
plt.loglog(ranks, frequencies, marker="o", linestyle="none", color="blue", label="Observed")
# 拟合 Zipf’s Law 直线
slope, intercept = np.polyfit(np.log(ranks), np.log(frequencies), 1)
plt.plot(ranks, np.exp(intercept) * ranks ** slope, color="red", linestyle="dashed", label=f"Fit: slope={slope:.2f}")
plt.xlabel("Rank (log scale)")
plt.ylabel("Frequency (log scale)")
plt.title("Zipf's Law in Word Frequency")
plt.legend()
plt.show()
齐普夫定律在 NLP 和语言学研究中非常重要,它帮助我们理解 语言的本质,并在文本分析、信息检索和机器学习等领域有着广泛应用。