Python小程序—文本詞頻統計


第一部分 英文文本分析詞頻

以Hamlet文本為例,文本下載鏈接: https://python123.io/resources/pye/hamlet.txt

#CalHamletV1.py
#hamlet文本下載鏈接:https://python123.io/resources/pye/hamlet.txt
def getText():     #對文本歸一化處理(變為小寫,特殊字符替換為空格)
    txt = open("hamlet.txt","r").read()
    txt = txt.lower()   #所有字母變為小寫
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_{|}`~':
        txt= txt.replace(ch," ")  #用空格代替各種特殊字符
    return txt
hamletTxt=getText()
words =hamletTxt.split()  #根據空格分隔每一個字母
counts ={}
for word in words:
    counts[word] = counts.get(word,0) + 1  #如果鍵不存在字典中,給出默認值
items = list(counts.items())   #變為列表類型,便於排序操作
items.sort(key=lambda x:x[1], reverse=True)   #對第二個元素,從大到小倒排
#sort方法小知識:參數lambda用來指定列表中使用哪一個多元選項的列作為排序列,默認的排序是從小到大;reverse設為True,則排序從大到小
for i in range(10):   #輸出最多的10個單詞
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))
CalHamletV1 Code

運行結果:

 

第二部分 中文文本分析詞頻

 以《三國演義》文本為例,進行人物出場次數統計,文本下載鏈接:https://python123.io/resources/pye/threekingdoms.txt

分析:與英文詞頻分析不同,中文文本分詞需要借助第三方庫“jieba”,在cmd下輸入“pip install jieba”即可安裝該庫。

#CalThreeKingdomsV1.py
import jieba
txt = open("threekingdoms.txt","r",encoding="utf-8").read()
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))
CalThreeKingdomsV1 Code

運行結果:

 

 分析結果:發現“孔明”和“孔明曰”是同一個人,分詞時卻分成兩個詞組;另外,“二人”、“卻說”等並不是人名。因此,需要將詞頻與任務相關聯,面向問題修改程序。

解決思路:1.排除詞庫;2.名稱關聯。通過不斷顯示結果進行優化程序。

#CalThreeKingdomsv2.py
import jieba
txt = open("threekingdoms.txt","r",encoding="utf-8").read()
excludes = {"將軍","卻說","荊州","二人","不可","不能","如此"}
words = jieba.lcut(txt)
counts={}
for word in words:
    if len(word) == 1:
        continue
    elif word =="諸葛亮" or word == "孔明曰":
        rword = "孔明"
    elif word =="關公"or word =="雲長":
        rword ="關羽"
    elif word =="玄德" or word =="玄德曰":
        rword ="劉備"
    elif word == "孟德"or word =="丞相":
        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)
for i in range(10):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))
CalThreeKingdomsv2 Code

運行結果:

 

 接着,需要繼續優化程序,把“商議”、“如何”等詞語加到排除集合excludes中。

 

最終最終,可以得出《三國演義》人物出場統計結果為(前20):

曹操、孔明、劉備、關羽、張飛、呂布、趙雲、孫權、司馬懿、周瑜、袁紹、馬超、魏延、黃忠、姜維、馬岱、龐德、孟獲、劉表、夏侯惇。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM