统计《三国演义》中人物出场次数。
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))