
说明
- 导入txt数据,生成词频+词云图
- 如果词云图乱码就是缺少这个字体 'E:/msyh.ttc' 这个字体文件需要下载 自己百度下载就行
# 导入所需库
import jieba
import wordcloud
from collections import Counter
import matplotlib.pyplot as plt
# 读取txt文档
with open('E:/甄嬛传.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba进行分词
words = jieba.cut(text)
# 统计词频
word_count = Counter()
for word in words:
if len(word) >= 2: # 仅统计长度大于等于2的词语
word_count[word] += 1
# 获取词频前100的词汇
top100_words = word_count.most_common(100)
# 输出结果到txt文档
with open('甄嬛传词频.txt', 'w', encoding='utf-8-sig') as f:
for word, count in top100_words:
f.write(f'{word}: {count}\n')
# 生成词云图
wc = wordcloud.WordCloud(
width=800, height=600, background_color='white',
font_path='E:/msyh.ttc' # 使用微软雅黑字体
)
wc.generate_from_frequencies(word_count)
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
# 导出词云图
wc.to_file('甄嬛传词云图.png')