Python jieba 中文分詞與詞頻統(tǒng)計的操作
我就廢話不多說了,大家還是直接看代碼吧~
#! python3# -*- coding: utf-8 -*-import os, codecsimport jiebafrom collections import Counter def get_words(txt): seg_list = jieba.cut(txt) c = Counter() for x in seg_list: if len(x)>1 and x != ’rn’: c[x] += 1 print(’常用詞頻度統(tǒng)計結(jié)果’) for (k,v) in c.most_common(100): print(’%s%s %s %d’ % (’ ’*(5-len(k)), k, ’*’*int(v/3), v)) if __name__ == ’__main__’: with codecs.open(’19d.txt’, ’r’, ’utf8’) as f: txt = f.read() get_words(txt)
樣本:十九大報告全文
常用詞頻度統(tǒng)計結(jié)果 發(fā)展 ********************************************************************** 212 中國 ******************************************************** 168 人民 **************************************************** 157 建設(shè) ************************************************* 148 社會主義 ************************************************ 146 堅持 ******************************************* 130 國家 ****************************** 90 全面 ***************************** 88 制度 *************************** 83 實現(xiàn) *************************** 83 推進 *************************** 81 政治 ************************** 80 社會 ************************** 80 特色 ************************** 79 加強 *********************** 71 體系 ********************** 68 文化 ********************** 66 我們 ********************* 64 時代 ********************* 63 必須 ******************** 61 經(jīng)濟 ******************* 59 偉大 ******************* 58 完善 ***************** 51 我國 **************** 50 推動 *************** 47 現(xiàn)代化 *************** 47 安全 *************** 46 更加 ************** 44 民主 ************** 44
補充:jieba讀取txt文檔并進行分詞、詞頻統(tǒng)計,輸出詞云圖
代碼實現(xiàn)
# 庫的引用import jiebaimport matplotlib as mplimport matplotlib.pyplot as pltfrom wordcloud import WordCloud#定義一個空字符串final = ''#文件夾位置filename = r'D:pythonpra推薦系統(tǒng)1-500.txt' #打開文件夾,讀取內(nèi)容,并進行分詞with open(filename,’r’,encoding = ’utf-8’) as f: for line in f.readlines(): word = jieba.cut(line) for i in word: final = final + i +' '
運行結(jié)果
# 圖云打印word_pic = WordCloud(font_path = r’C:WindowsFontssimkai.ttf’,width = 2000,height = 1000).generate(final)plt.imshow(word_pic)#去掉坐標(biāo)軸plt.axis(’off’)#保存圖片到相應(yīng)文件夾plt.savefig(r’D:pythonpra6.png’)
圖云輸出圖
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
