[Python] Three Kingdoms word frequency statistics

import jieba 
txt = open('C:/Users/eternal/Desktop/threekingdoms.txt','r',encoding='UTF-8').read() #modify the txt file encoding format in advance utf-8
excludes = { 'General','but said','Jingzhou','two people','no','can't','so'} #wrong name
words = jieba.lcut(txt)
print(words)
counts = {}
for word in words:
if len(word) == 1:
continue
elif word == 'Zhuge Liang' or word == 'Kong Ming Yue':
rword = 'Kong Ming'
elif word == 'Guan Gong' or word == 'Cloud Chang' :
rword == 'Guan Yu'
elif word == 'Xuande' or word == 'Xuande Yue':
rword = 'Liu Bei'
elif word == 'Meng De' or word == 'Prime Minister':
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(items)
for i in range(10):
word,count = items[i]
print('{0:<10}{1:>5}'.format(word,count))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325228904&siteId=291194637