您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 如何用Python写一个词频统计小项目
词频统计是自然语言处理的基础任务之一,它能帮助我们快速分析文本中的关键词分布。本文将手把手教你用Python实现一个完整的词频统计工具,包含文件读取、文本预处理、统计分析和可视化功能。
## 一、项目功能设计
我们的词频统计工具将实现以下核心功能:
1. 支持多种文本格式输入(txt/csv/json)
2. 中文/英文文本分词处理
3. 停用词过滤
4. 词频统计与排序
5. 结果可视化展示
6. 统计结果导出
## 二、开发环境准备
```python
# 所需库安装
pip install jieba # 中文分词
pip install wordcloud # 词云生成
pip install matplotlib pandas
def read_file(file_path):
"""支持多种文本格式读取"""
if file_path.endswith('.txt'):
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
elif file_path.endswith('.csv'):
import pandas as pd
return pd.read_csv(file_path).to_string()
elif file_path.endswith('.json'):
import json
with open(file_path, 'r') as f:
return json.load(f)
else:
raise ValueError("Unsupported file format")
import re
import jieba
from collections import Counter
def preprocess_text(text, language='ch'):
"""文本清洗和分词处理"""
# 去除特殊字符
text = re.sub(r'[^\w\s]', '', text.lower())
if language == 'ch':
# 中文分词
words = jieba.lcut(text)
else:
# 英文分词
words = text.split()
return words
def load_stopwords(stop_file='stopwords.txt'):
"""加载停用词表"""
with open(stop_file, 'r', encoding='utf-8') as f:
return set([line.strip() for line in f])
def remove_stopwords(words, stopwords):
"""过滤停用词"""
return [w for w in words if w not in stopwords and len(w) > 1]
def word_frequency(words, top_n=20):
"""统计词频并返回最高频的N个词"""
return Counter(words).most_common(top_n)
import matplotlib.pyplot as plt
from wordcloud import WordCloud
def plot_wordcloud(word_freq):
"""生成词云图"""
wc = WordCloud(
font_path='simhei.ttf',
background_color='white',
width=800,
height=600
).generate_from_frequencies(dict(word_freq))
plt.imshow(wc)
plt.axis('off')
plt.show()
def plot_bar(word_freq):
"""绘制柱状图"""
words, counts = zip(*word_freq)
plt.barh(words, counts)
plt.xlabel('出现次数')
plt.title('词频统计')
plt.tight_layout()
plt.show()
def main(file_path, language='ch', top_n=20):
# 1. 读取文件
text = read_file(file_path)
# 2. 预处理和分词
words = preprocess_text(text, language)
# 3. 停用词过滤
stopwords = load_stopwords()
words = remove_stopwords(words, stopwords)
# 4. 词频统计
word_freq = word_frequency(words, top_n)
# 5. 结果展示
print("Top {} 高频词:".format(top_n))
for word, count in word_freq:
print(f"{word}: {count}")
# 6. 可视化
plot_bar(word_freq)
plot_wordcloud(word_freq)
return word_freq
if __name__ == '__main__':
# 统计中文新闻词频
result = main('news.txt', language='ch')
# 统计英文小说词频
result = main('novel.txt', language='en', top_n=30)
jieba.load_userdict()
通过这个约100行的Python项目,我们实现了完整的词频统计流程。该项目不仅可以帮助你快速分析文档关键词,还能作为学习Python文本处理的入门案例。建议在此基础上继续扩展功能,比如添加PDF文件支持或开发GUI界面,让项目更加实用。
完整代码已上传GitHub:https://github.com/example/word-frequency-analyzer “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。