《红楼梦》是一篇鸿篇巨制,里面出现了几百个各具特色的人物。每次读这本经典作品都会想一个问题,全书这些人物谁出场最多呢?我们来用Python进行回答。
import jieba
f=open("红楼梦.txt","r",encoding="utf-8")
txt=f.read()
f.close()
words=jieba.lcut(txt)
counts={}
for word in words:
if len(word)==1:
continue
else:
counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(15):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))
输出排序前15的单词,输出结果如下:
与英文词频统计类似,需要排除一些与人名无关的词汇,比如“什么”“一个”等等。进一步完善代码。
需要增加排除词库excludes
import jieba
excludes={"什么","一个","我们","那里","你们","如今",\
"说道",