读取三国演义.txt文件,分析统计其中人物出现的频率,使用Matplotlib绘制词频统计结果,生成人物词云。

读取三国演义.txt文件,分析统计其中人物出现的频率,使用Matplotlib绘制词频统计结果,生成人物词云。


提示:以下是本篇文章正文内容,下面案例可供参考

1.分词,并统计出现的次数

import jieba

m = open('三国演义(白话文版).txt', 'r', encoding='utf-8')
s = m.read()
m.close()

with open('中文停用词库.txt', 'r', encoding='utf-8') as f:
    stopwords = f.read().split()

word_list = jieba.cut(s)
# 使用jieba.cut进行分词

dic = {}
for word in word_list:

    if word not in stopwords and len(word) > 1:
        dic[word] = dic.get(word, 0) + 1

fre_list = sorted(dic.items(), key=lambda x: x[1], reverse=True)
st = ''
with open('三国词频_人名.txt', 'w', encoding='utf-8') as f:
    for word, fre in fre_list:
        st += '{} {}\n'.format(word, fre)
    f.write(st)
    # 在循环结束后写入文件

结果:

2.生成词云

import jieba
import matplotlib
import wordcloud
from matplotlib import pyplot as plt

f = open('三国词频_人名.txt', 'r', encoding='utf-8')
text = f.read()
wcloud = wordcloud.WordCloud(font_path='C:/Windows/Fonts/simkai.ttf',background_color="white", width=1000, max_words=500, height=860, margin=2).generate(text)
plt.rcParams["font.sans-serif"] = ["SimHei"]  # 设置字体
wcloud.to_file("三国词频cloud.png")
f.close()

结果:

解决simkai字体找不到的问题:

下载,点开,安装

我把包附上了,看看能不能下载

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值