大家好,我是人间富贵花下的贫穷草,简称人间富贵草。
jieba(结巴)作为一个优秀的第三方中文分词函数库,今天我们就把它拉出来溜溜。
《三国演义》txt文本下载地址:https://www.shutxt.com/e/DownSys/doaction.php?enews=DownSoft&classid=18&id=750&pathid=0&pass=3db1f2cfcfe0f9b563d489e0498444b1&p=:::www.shutxt.com
鸿篇巨制《三国演义》到底谁的出场次数最多呢?
#《三国演义》人物出场统计,把此py文件和《三国演义》文本放在同一文件夹
import jieba
#打开txt文件并且读取全部文本
file = open("三国演义.txt","r+",encoding='utf-8').read()
#jieba精确模式分词,返回列表words
words =jieba.lcut(file)
#核心思路如下,把人名当做字典key,出场次数当做value
dict_counts = {}
for word in words:
if len(word) == 1: #排除单一字符如“的/地/也“的干扰
continue
else: #dict_counts.get(word,0)+1表示已存在word则返回对应value值并+1,不存在就返回0再+1
dict_counts[word] = dict_counts.get(word,0)+1 #d.get()的用法可见上篇文章
items = list(dict_counts.items())
#按出场次数降序排序
items.sort(key=lambda x:x[1],reverse=True)
#输出top20名
for i in range(20):
word,count = items[i]
print("人物:{0:<10}出场次数:{1:>5}".format(word,count))
>>>
========== RESTART: D:/Program Files/Python/Python_Files/jieba/f_print.py ==========
人物:曹操 出场次数: 936
人物:孔明 出场次数: 831
人物:将军 出场次数: 772
人物:却说 出场次