python导入txt数据-生成词频+词云图

查看 41|回复 1
作者:qq632280928   
之前做的爬虫,用到了词频分析+词云图现在代码分享给大家
导入txt数据,生成词频+词云图
如果词云图乱码就是缺少这个字体
[color=]'E:/msyh.ttc' 这个字体文件需要下载 自己百度下载就行
[color=]效果图


微信图片_20230529160337.png (240.86 KB, 下载次数: 0)
下载附件
2023-5-29 16:04 上传

[color=]下面是代码
[Python] 纯文本查看 复制代码# 导入所需库
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')

词频, 云图

PengXP   

感谢楼主开源精神
您需要登录后才可以回帖 登录 | 立即注册

返回顶部