程序解决问题描述如下:
打开《三国演义》文本文件,使用jieba库对《三国演义》全篇进行分词处理,实现统计人物出场次数最多的前五名之后,并以柱状图表示。使用matplotlib库绘制柱状图,并将其以图片形式保存到电脑磁盘中。
程序代码如下:
import jieba
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei'#matplotlib库绘制图像的字体设置
matplotlib.rcParams['font.sans-serif']=['SimHei']
excludes = {"将军", "却说", "荆州", "二人", "不可", "不能", "如此"}
txt = open("三国演义.txt", "r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
elif word == "诸葛亮" or word == "孔明曰" or word == "卧龙":
rword = "孔明"
elif word == "关公" or word == "云长" or word == "美髯公":
rword = "关羽"
elif word == "玄德" or word == "玄德曰" or word == "刘皇叔":
rword = "刘备"
elif word == "孟德" or word == "丞相" or word == "曹贼":
rword = "曹操"
elif word == "翼德" or word == "猛张飞" or word == "张翼德":
rword = "张飞"
else:
rword = word
counts[rword] = counts.get(rword, 0) + 1
for word in excludes:
del (counts[word])
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
print("三国人物出场次数统计:")
for i in range(5):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
qww=[]
qwc=[]
for k in range(5):
qwwk,qwck=items[k]
qww.append(qwwk)
qwc.append(qwck)
plt.figure()
plt.bar(qww,qwc)
for a,b,i in zip(qww,qwc,range(5)):
plt.text(a,b+0.01,qwc[i],ha='center',fontsize=10)
plt.ylabel('出场次数',fontsize=12)
plt.xlabel('人物',fontsize=12)
plt.title('《三国演义》出场次数前五柱状图')
plt.savefig('三国出场柱状图.png')
plt.show()
程序运行结果如下:
看到这里的小伙伴别忘了点个赞再走哦!
关注博主学习更多Python程序设计知识!