编程基础第一期《4-30》实现统计文本文件单词频率(
.txt
)
文本分析是自然语言处理(NLP)中的基础任务,而词频统计则是文本分析的入门级应用。通过词频分析,我们可以快速了解文本的主题倾向、关键信息分布以及语言使用习惯。本文将带你实现一个简单而实用的文本词频统计工具,非常适合Python初学者练手。
.txt
格式文本文件的词频分析import re
from collections import defaultdict
def word_frequency(file_path, top_n=None):
"""
统计文本文件中的单词频率
:param file_path: 文本文件路径
:param top_n: 显示前N个高频词,默认显示全部
:return: 排序后的单词频率列表
"""
# 读取文件内容
try:
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read().lower() # 转为小写
except FileNotFoundError:
print(f"错误:文件 {file_path} 未找到")
return []
except UnicodeDecodeError:
print("错误:文件编码不支持,请尝试使用其他编码(如gbk)")
return []
# 使用正则表达式提取单词(包括带连字符的单词)
words = re.findall(r"\b[a-zA-Z'-]+\b", text)
# 统计词频
frequency = defaultdict(int)
for word in words:
frequency[word] += 1
# 按频率排序
sorted_words = sorted(frequency.items(), key=lambda x: x[1], reverse=True)
# 输出结果
print(f"\n总共有 {len(words)} 个单词,其中唯一单词 {len(sorted_words)} 个")
print("排名 | 单词\t\t频率\t占比")
print("-" * 40)
total_words = len(words)
for rank, (word, count) in enumerate(sorted_words[:top_n], 1):
percentage = (count / total_words) * 100
print(f"{rank:4} | {word:12} {count:6} \t{percentage:.2f}%")
return sorted_words
if __name__ == "__main__":
# 使用示例
file_path = input("请输入文本文件路径:").strip()
top_n = input("要显示前多少个高频词(默认全部):").strip()
top_n = int(top_n) if top_n.isdigit() else None
word_frequency(file_path, top_n)
导入必要模块:
re
:提供正则表达式支持,用于精确提取单词defaultdict
:特殊字典类型,当键不存在时提供默认值,简化词频统计核心函数设计:
\b[a-zA-Z'-]+\b
提取英文单词(包括带连字符和撇号的复杂形式)defaultdict
高效统计词频sorted()
函数按词频排序用户交互:
将以下文本保存为txt文件,然后运行程序,输入文件路径即可看到分析结果:
如果你在心里埋下了一颗争气的种子,那么努力就变成了必修课,无论再苦再累,请你跑到终点再哭泣,成长本来就是一个孤立无援的过程,难过的从来不是路,而是你心里的那一关,能困住你的的只有你自己!