# 如何用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。