1. 程式人生 > 其它 >統計《三國演義》中人物出場次數。

統計《三國演義》中人物出場次數。

 1 #三國演義人物出場次數統計
 2 import jieba
 3 excludes = {"將軍","卻說","荊州","二人","不可","不能","如此","商議","軍士","如何","主公","軍馬","左右",}
 4 with open("./三國演義.txt", "r", )as file:
 5     txt=file.read()
 6 words=jieba.lcut(txt)
 7 counts = {}
 8 for word in words:
 9     if len(word) == 1:
10         continue
11     elif word == "
諸葛亮" or word == "孔明曰": 12 rword = "孔明" 13 elif word == "關公" or word == "雲長": 14 rword = "關羽" 15 elif word == "玄德" or word == "玄德曰": 16 rword = "劉備" 17 elif word == "孟德" or word == "丞相": 18 rword = "曹操" 19 else: 20 rword = word 21 counts[rword] = counts.get(rword,0) + 1 22
for word in excludes: 23 del(counts[word]) 24 items = list(counts.items()) 25 items.sort(key=lambda x:x[1], reverse=True) 26 for i in range(5): 27 word, count=items[i] 28 print("{0:<10}{1:>5}".format(word, count))