3. 文件单词统计
任务说明
读取一个文本文件,统计其中每个单词出现的次数,并按频率降序输出前10个单词。单词定义为由字母或数字组成的连续字符序列,统计时不区分大小写。
实现代码
import re
from collections import Counter
def count_words(filename, top_n=10):
"""统计文件中每个单词出现次数,返回频率最高的前top_n个单词列表。"""
try:
with open(filename, 'r', encoding='utf-8') as f:
text = f.read()
except FileNotFoundError:
print(f"错误:文件 {filename} 不存在")
return []
# 提取单词(字母或数字组成的连续序列),统一转为小写
words = re.findall(r'[a-zA-Z0-9]+', text.lower())
# 统计词频
word_counts = Counter(words)
# 按频率降序,同频按字母升序,取前top_n个
top_words = word_counts.most_common(top_n)
return top_words
if __name__ == "__main__":
# 创建示例文件用于演示
sample_text = """Python is a programming language.
Python is easy to learn.
Programming with Python is fun.
Learn Python step by step."""
with open("sample.txt", "w", encoding="utf-8") as f:
f.write(sample_text)
# 统计并输出结果
result = count_words("sample.txt", top_n=10)
for word, count in result:
print(f"{word}: {count}")
运行与验证
将上述代码保存为 word_count.py,在命令行执行 python word_count.py。程序会先创建示例文件 sample.txt,然后统计其中单词频率并输出前10个。
预期输出(基于示例文本的确定性结果):
python: 4
is: 3
learn: 2
programming: 2
a: 1
easy: 1
fun: 1
language: 1
step: 1
to: 1
验证方法:
- 检查输出是否包含上述10个单词及其对应次数,且顺序为频率降序(同频按字母序)。
- 将
sample.txt替换为任意其他文本文件,修改count_words调用参数,确认程序能正确统计新文件的词频。 - 若文件不存在,程序应打印错误提示并返回空列表。
判定标准
- 程序能正确读取指定文本文件,并输出频率最高的前10个单词及其出现次数。
- 统计结果与人工核对一致:示例文件中 "python" 出现4次,"is" 出现3次,"learn" 和 "programming" 各2次,其余单词各1次。
- 输出顺序严格按频率降序排列,同频单词按字母升序排列。