Python實現簡單中文詞頻統計示例


簡單統計一個小說中哪些個漢字出現的頻率最高:

import codecs
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默認字體
mpl.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負號'-'顯示為方塊的問題
 
word = []
counter = {}
 
with codecs.open('data.txt') as fr:
 for line in fr:
  line = line.strip()
  if len(line) == 0:
   continue
  for w in line:
   if not w in word:
    word.append(w)
   if not w in counter:
    counter[w] = 0
   else:
    counter[w] += 1
 
counter_list = sorted(counter.items(), key=lambda x: x[1], reverse=True)
 
print(counter_list[:50])
 
label = list(map(lambda x: x[0], counter_list[:50]))
value = list(map(lambda y: y[1], counter_list[:50]))
 
plt.bar(range(len(value)), value, tick_label=label)
plt.show()

結果如下:

[(',', 288508), ('。', 261584), ('的', 188693), ('陳', 92565), ('歡', 92505), ('不', 91234), ('是', 90562), ('了', 86931), ('一', 79059), ('着', 77997), ('他'
, 71695), ('這', 63580), ('人', 61210), ('“', 59719), ('”', 59115), ('有', 56054), ('就', 52862), ('個', 49097), ('都', 46850), ('你', 45400), ('來', 42659),
 ('我', 40057), ('在', 37676), ('們', 36966), ('到', 36351), ('說', 35828), ('還', 35260), ('么', 32601), ('下', 31742), ('地', 30692), ('得', 29904), ('上', 2
9627), ('看', 28408), ('沒', 28333), ('出', 27937), ('道', 27732), ('大', 27012), ('?', 26729), ('那', 26589), ('要', 26076), ('子', 25035), ('自', 24012), ('
點', 23942), ('好', 21345), ('想', 21242), ('里', 20915), ('面', 20661), ('她', 20313), ('過', 20304), ('話', 20110)]


免責聲明!

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



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