Python 英文词频统计
综合实例 044
题目
统计一段英文文本中出现频率最高的单词,忽略大小写、标点和常见停用词。
参考代码
import re
from collections import Counter
text = """
Python is a programming language that lets you work quickly and integrate
systems more effectively. Python is powerful, and fast; plays well with
others; runs everywhere; is friendly and easy to learn. Python is open.
"""
stop_words = {"is", "a", "and", "that", "you", "with", "to", "more"}
words = re.findall(r"[a-z']+", text.lower())
freq = Counter(w for w in words if w not in stop_words)
print(f"共 {len(words)} 个单词,去除停用词后不同单词 {len(freq)} 个")
for word, n in freq.most_common(5):
print(f"{word:<12}{'■' * n} {n}")执行以上代码输出结果为:
共 35 个单词,去除停用词后不同单词 20 个
python ■■■ 3
programming ■ 1
language ■ 1
lets ■ 1
work ■ 1代码解析
用正则 [a-z']+ 提取单词能自动跳过标点。Counter.most_common 直接给出排名,再用字符 ■ 画一个简单的文字柱状图。