日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

【Python】《三国演义》人物出场统计

發(fā)布時間:2023/12/18 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python】《三国演义》人物出场统计 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

jieba是Python中一個重要的第三方中文分詞函數(shù)庫,由于是第三方庫,不是安裝包自帶,需要通過pip指令安裝。

jieba庫的解析

利用jieba庫進行文本詞頻統(tǒng)計

《三國演義》人物出場統(tǒng)計

import jieba txt = open("三國演義.txt", "r", encoding='utf-8').read() words = jieba.lcut(txt) counts = {} for word in words:if len(word) == 1:continueelse: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))

運行結(jié)果:

由于在小說中,同一個人物會有不同的名字,這種情況需要進行整合處理。同時,需要排除一些人名無關(guān)詞匯,如“卻說”、“將軍”等,還需對上述代碼進行優(yōu)化。
優(yōu)化后的代碼如下:

import jieba excludes={"將軍","卻說","二人","不可","荊州","不能","如此"} txt=open("三國演義.txt","r",encoding='utf-8').read() words=jieba.lcut(txt) counts={} for word in words:if len(word)==1: continueelif word=="諸葛亮" or word=="孔明曰":rword="孔明"elif word=="關(guān)公" or word=="云長":rword="關(guān)羽"elif word=="玄德" or word=="玄德曰":rword="劉備"elif word=="孟德" or word=="丞相":rword="曹操"else:rword=wordcounts[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) for i in range(5):word,count=items[i]print("{0:<10}{1:>5}".format(word,count))

運行結(jié)果:

總結(jié)

以上是生活随笔為你收集整理的【Python】《三国演义》人物出场统计的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。