Python词频统计工具全解析
目录
一、程序工作流程
二、完善代码
1. 导入库
2. WordFrequencyAnalyzer类
初始化方法 __init__
文本加载方法
核心文本处理方法 _process_text
信息获取方法
结果展示方法
3. 主函数 main()
4. 程序入口
5.关键功能解析
文本处理
词频统计
可视化展示
多行文本输入
三、完整代码
一、程序工作流程
-
启动程序,显示主菜单
-
用户选择加载文本的方式:
-
直接输入文本
-
从文件加载
-
-
程序处理文本,统计词频
-
用户可以选择:
-
查看统计摘要
-
查询特定单词频率
-
查看所有单词频率
-
导出结果到CSV
-
可视化展示常见单词
-
-
用户可以选择退出程序
二、完善代码
1. 导入库
import re
from collections import Counter
import matplotlib.pyplot as plt
re
: Python的正则表达式库,用于文本处理
Counter
: 来自collections模块,用于高效计数
matplotlib.pyplot
: 用于数据可视化
2. WordFrequencyAnalyzer类
这是程序的核心类,负责文本分析和统计:
初始化方法 __init__
def __init__(self):self.word_freq = Counter() # 存储单词频率的计数器self.total_words = 0 # 总单词数self.unique_words = 0 # 唯一单词数self.most_common = [] # 最常见的单词列表self.text_source = "未加载文本" # 文本来源信息
文本加载方法
def load_text(self, text):"""从字符串加载文本"""self.text_source = "直接输入的文本"self._process_text(text)def load_file(self, filename):"""从文件加载文本"""try:with open(filename, 'r', encoding='utf-8') as file:text = file.read()self.text_source = filenameself._process_text(text)return Trueexcept FileNotFoundError:print(f"错误: 文件 '{filename}' 未找到")return Falseexcept Exception as e:print(f"读取文件时出错: {e}")return False
-
load_text
: 从用户输入的字符串加载文本 -
load_file
: 从文件加载文本,处理文件读取错误
核心文本处理方法 _process_text
def _process_text(self, text):"""处理文本并统计词频"""# 转换为小写并移除标点符号cleaned_text = re.sub(r'[^\w\s]', '', text.lower())# 分割单词words = cleaned_text.split()# 更新统计self.word_freq = Counter(words)self.total_words = len(words)self.unique_words = len(self.word_freq)self.most_common = self.word_freq.most_common()
这是程序的核心处理逻辑:
-
使用正则表达式移除标点符号
-
将所有文本转为小写
-
使用split()分割单词
-
使用Counter统计词频
-
计算总单词数和唯一单词数
-
获取最常见的单词列表
信息获取方法
def get_total_words(self):"""获取总单词数"""return self.total_wordsdef get_unique_words(self):"""获取唯一单词数"""return self.unique_wordsdef get_most_common(self, n=10):"""获取出现频率最高的前n个单词"""return self.most_common[:n]def get_word_frequency(self, word):"""获取特定单词的出现频率"""return self.word_freq.get(word.lower(), 0)
这些方法提供对统计结果的访问接口。
结果展示方法
def print_summary(self):"""打印统计摘要"""# 显示基本信息# 显示最常见的10个单词def print_all_frequencies(self):"""打印所有单词及其频率"""# 按字母顺序显示所有单词及其出现次数def export_to_csv(self, filename="word_frequency.csv"):"""将词频统计导出到CSV文件"""# 创建CSV文件,包含单词、出现次数和频率def visualize_top_words(self, n=15):"""可视化展示前n个最常见单词"""# 使用matplotlib创建水平条形图
这些方法提供了多种结果展示方式:
-
控制台打印摘要
-
显示所有单词频率
-
导出到CSV文件
-
可视化展示
3. 主函数 main()
这是程序的入口点,提供用户交互界面:
def main():analyzer = WordFrequencyAnalyzer() # 创建分析器实例# 显示菜单while True:# 显示选项菜单choice = input("\n请选择操作: ")# 处理用户选择if choice == '1': # 输入文本# 获取多行输入# 处理文本elif choice == '2': # 从文件加载# 获取文件名# 加载文件elif choice == '3': # 查看统计摘要# 检查是否有数据# 显示摘要elif choice == '4': # 查询单词频率# 获取单词# 查询并显示结果elif choice == '5': # 查看所有单词频率# 检查是否有数据# 显示所有单词频率elif choice == '6': # 导出到CSV# 获取文件名# 导出数据elif choice == '7': # 可视化展示# 获取要显示的单词数量# 显示图表elif choice == '8': # 退出breakelse: # 无效选择print("无效选择,请重新输入")
4. 程序入口
if __name__ == "__main__":main()
当直接运行此Python文件时,会调用main()函数启动程序。
5.关键功能解析
文本处理
cleaned_text = re.sub(r'[^\w\s]', '', text.lower())
words = cleaned_text.split()
使用正则表达式
[^\w\s]
匹配所有非单词字符(字母、数字、下划线)和非空白字符将这些字符替换为空字符串,从而移除标点符号
将文本转为小写,使"Word"和"word"被视为同一个单词
使用split()分割单词
词频统计
self.word_freq = Counter(words)
Counter是Python的高效计数工具,可以快速统计每个单词的出现次数
可视化展示
plt.figure(figsize=(12, 8))
plt.barh(top_words[::-1], counts[::-1], color='skyblue')
-
创建水平条形图
-
使用[::-1]反转列表,使最常见的单词显示在顶部
-
设置图表大小和颜色
多行文本输入
text = input("请输入文本(输入空行结束):\n")
lines = []
while text.strip():lines.append(text)text = input()
full_text = "\n".join(lines)
-
允许用户输入多行文本
-
当用户输入空行时结束输入
-
将所有行连接成完整文本
这个程序提供了一个完整的词频分析解决方案,从文本输入、处理、分析到结果展示和导出,功能全面且用户友好。
三、完整代码
import re
from collections import Counter
import matplotlib.pyplot as pltclass WordFrequencyAnalyzer:def __init__(self):self.word_freq = Counter()self.total_words = 0self.unique_words = 0self.most_common = []self.text_source = "未加载文本"def load_text(self, text):"""从字符串加载文本"""self.text_source = "直接输入的文本"self._process_text(text)def load_file(self, filename):"""从文件加载文本"""try:with open(filename, 'r', encoding='utf-8') as file:text = file.read()self.text_source = filenameself._process_text(text)return Trueexcept FileNotFoundError:print(f"错误: 文件 '{filename}' 未找到")return Falseexcept Exception as e:print(f"读取文件时出错: {e}")return Falsedef _process_text(self, text):"""处理文本并统计词频"""# 转换为小写并移除标点符号cleaned_text = re.sub(r'[^\w\s]', '', text.lower())# 分割单词words = cleaned_text.split()# 更新统计self.word_freq = Counter(words)self.total_words = len(words)self.unique_words = len(self.word_freq)self.most_common = self.word_freq.most_common()def get_total_words(self):"""获取总单词数"""return self.total_wordsdef get_unique_words(self):"""获取唯一单词数"""return self.unique_wordsdef get_most_common(self, n=10):"""获取出现频率最高的前n个单词"""return self.most_common[:n]def get_word_frequency(self, word):"""获取特定单词的出现频率"""return self.word_freq.get(word.lower(), 0)def print_summary(self):"""打印统计摘要"""print("\n===== 文本词频统计摘要 =====")print(f"文本来源: {self.text_source}")print(f"总单词数: {self.total_words}")print(f"唯一单词数: {self.unique_words}")print(f"词汇丰富度: {self.unique_words/self.total_words:.2%}")# 打印最常见的10个单词print("\n最常见的10个单词:")for i, (word, count) in enumerate(self.get_most_common(10), 1):print(f"{i}. {word}: {count}次 ({count/self.total_words:.2%})")def print_all_frequencies(self):"""打印所有单词及其频率"""print("\n===== 所有单词频率 =====")for word, count in sorted(self.word_freq.items()):print(f"{word}: {count}次")def export_to_csv(self, filename="word_frequency.csv"):"""将词频统计导出到CSV文件"""try:with open(filename, 'w', encoding='utf-8') as file:file.write("单词,出现次数,频率\n")for word, count in self.most_common:frequency = count / self.total_wordsfile.write(f"{word},{count},{frequency:.6f}\n")print(f"词频统计已导出到 {filename}")return Trueexcept Exception as e:print(f"导出失败: {e}")return Falsedef visualize_top_words(self, n=15):"""可视化展示前n个最常见单词"""if not self.most_common:print("没有可用的数据")returntop_words = [word for word, _ in self.most_common[:n]]counts = [count for _, count in self.most_common[:n]]plt.figure(figsize=(12, 8))plt.barh(top_words[::-1], counts[::-1], color='skyblue')plt.xlabel('出现次数')plt.title(f'文本中最常见的 {n} 个单词')plt.tight_layout()plt.show()def main():analyzer = WordFrequencyAnalyzer()print("===== 文本词频统计器 =====")print("1. 输入文本")print("2. 从文件加载")print("3. 查看统计摘要")print("4. 查询单词频率")print("5. 查看所有单词频率")print("6. 导出到CSV")print("7. 可视化展示")print("8. 退出")while True:choice = input("\n请选择操作: ")if choice == '1':text = input("请输入文本(输入空行结束):\n")lines = []while text.strip():lines.append(text)text = input()full_text = "\n".join(lines)analyzer.load_text(full_text)print(f"已加载文本,共{analyzer.get_total_words()}个单词")elif choice == '2':filename = input("请输入文件名: ")if analyzer.load_file(filename):print(f"已从文件加载,共{analyzer.get_total_words()}个单词")elif choice == '3':if analyzer.total_words > 0:analyzer.print_summary()else:print("请先加载文本")elif choice == '4':if analyzer.total_words > 0:word = input("请输入要查询的单词: ").strip()count = analyzer.get_word_frequency(word)if count > 0:freq = count / analyzer.get_total_words()print(f"单词 '{word}' 出现了 {count} 次 (频率: {freq:.2%})")else:print(f"单词 '{word}' 未在文本中出现")else:print("请先加载文本")elif choice == '5':if analyzer.total_words > 0:analyzer.print_all_frequencies()else:print("请先加载文本")elif choice == '6':if analyzer.total_words > 0:filename = input("请输入导出文件名(默认: word_frequency.csv): ")if not filename:filename = "word_frequency.csv"analyzer.export_to_csv(filename)else:print("请先加载文本")elif choice == '7':if analyzer.total_words > 0:n = input("显示前多少个单词? (默认15): ")try:n = int(n) if n.strip() else 15analyzer.visualize_top_words(n)except ValueError:print("请输入有效数字")else:print("请先加载文本")elif choice == '8':print("感谢使用文本词频统计器!")breakelse:print("无效选择,请重新输入")if __name__ == "__main__":main()