本文介紹了python/56406.html">python/200497.html">python實現簡單中文詞頻統計示例,分享給大家,具體如下:
任務
簡單統計一個小說中哪些個漢字出現的頻率最高
知識點
1.文件操作
2.字典
3.排序
4.lambda
代碼
import codecsimport matplotlib.pyplot as pltfrom pylab import mplmpl.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] += 1counter_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()統計了一個11M的小說,結果如下:
[(',', 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)]

使用jieba先對中文文檔進行分詞處理
import sys reload(sys) sys.setdefaultencoding("utf-8") import jieba import jieba.analyse wf = open('clean_title.txt','w+') for line in open('/root/clean_data/clean_data.csv'): item = line.strip('/n/r').split('/t') //制表格切分 # print item[1] tags = jieba.analyse.extract_tags(item[1]) //jieba分詞 tagsw = ",".join(tags) //逗號連接切分的詞 wf.write(tagsw) wf.close() 輸出的clean_title.txt內容
郵輪,地中海,深度,羅馬,自由納西,柏林簽證,步行,三天,批準申根,手把手,簽證,申請,如何贊爆,法蘭,穿越,葡萄酒,風景,河谷,世界歐洲顏色,一種,國家,一個水族箱,帕勞,七日,上帝奧林匹亞,跑步圣托,
里尼,文明古國,探訪,愛琴海,魅力,希臘
2、統計詞頻
#!/usr/bin/python # -*- coding:utf-8 -*- word_lst = [] word_dict= {} with open('/root/clean_data/clean_title.txt') as wf,open("word.txt",'w') as wf2: //打開文件 for word in wf: word_lst.append(word.split(',')) //使用逗號進行切分 for item in word_lst: for item2 in item: if item2 not in word_dict: //統計數量 word_dict[item2] = 1 else: word_dict[item2] += 1 for key in word_dict: print key,word_dict[key] wf2.write(key+' '+str(word_dict[key])+'/n') //寫入文檔 結果:
最后 4
歐洲幽藍 1
集美 1
葡萄牙法多 1
工地 1
知道湖光山色 1
神圣 7
歐洲少女瑞士加游 1
根據詞匯數量排序查看:
cat word.txt |sort -nr -k 2|more
神圣 7
最后 4
歐洲幽藍 1
集美 1
葡萄牙法多 1
工地 1
知道湖光山色 1
歐洲少女瑞士加游 1
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答