Python NLPIR2016 与 wordcloud 结合生成中文词云
生活随笔
收集整理的這篇文章主要介紹了
Python NLPIR2016 与 wordcloud 结合生成中文词云
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前敘
該博文繼承之前的文章,進一步介紹NLPIR2016的使用,三個內(nèi)容(利用NLPIR 的發(fā)現(xiàn)新詞功能自動提取文本內(nèi)的新詞匯,解決worldcloud中英文混合只顯示中文的問題,NLPIR與worldcloud結(jié)合生成詞云)
寫作本博客需要一個小時,閱讀需要十二分鐘.
使用 NLPIR2016 獲取新詞
# 之前已經(jīng)展示過的代碼,介紹了NLPIR2016中獲取新詞的三個方式 # 獲得新詞,第二個參數(shù)控制新詞的個數(shù),排名按照TF-IDF(term frequency–inverse document frequency)排序 # 該功能可以和AddUserWord()方法配合使用,以更好地獲取分詞效果 # strs1 = GetNewWords(text,c_int(10),[c_char_p, c_int, c_bool]) # print strs1 # 獲得新詞(從txt文件中),第二個參數(shù)控制新詞的個數(shù),排名按照TF-IDF(term frequency–inverse document frequency)排序 # strs10 = GetFileNewWords(text,c_int(10),[c_char_p, c_int, c_bool]) # print strs10 # WindowsError: exception: access violation reading 0x0000000000000000 # 獲得關(guān)鍵詞,第二個參數(shù)控制新詞的個數(shù),排名按照TF-IDF(term frequency–inverse document frequency)排序 # strs2= GetKeyWords(text,c_int(10),[c_char_p, c_int, c_bool]) # print strs2# 我們將在代碼中利用內(nèi)存文本發(fā)現(xiàn)新詞的方法封裝起來 # 第一個參數(shù)是要加入而文本,第二個參數(shù)是獲取的新詞個數(shù) def getNewWordsByNLPIR(text, number):txt1 = GetNewWords(text, c_int(number), [c_char_p, c_int, c_bool])txt2 = txt1.split('#')txt3 = []txt4 = []txt5 = []for item2 in txt2:txt3.append(item2.encode('utf-8').split('/'))if txt3 != []:txt4.append(txt3)txt3 = []for i in txt4:for j in i:if j[0] != [] and j[0] != '':txt5.append(j[0])return txt5 #注意返回的是numpy的列表類型 # 然后你就可以通過一個簡單的循環(huán)將其添加進NLPIR的詞典 for item in NewWordAddUserWord(item)worldcloud 無法顯示中文的問題
博主在寫這篇博客時使用的是python2.7的,結(jié)果當NLPIR2016與wordcloud結(jié)合是,發(fā)現(xiàn)world只顯示text中的英文,而不顯示中文,而這和之前的結(jié)巴是不一樣的,并非制定了字體就可以解決的.于是我便將整個程序運行過程中的編碼格式都檢查了一遍,最后確認每個環(huán)節(jié)都是utf-8的編碼,而最后的輸入worldcloud使用的是wordcloud.generate(text.encode(‘utf-8’)),但是結(jié)果還是不行.
百般無奈之下,博主先停下先去讀讀其它書,便拿起一本數(shù)據(jù)清洗的書讀,當我在讀到其中一句話python2.x處理文本數(shù)據(jù)時最好在一開始讀取文件的時候就設(shè)定好編碼時,突然靈光一閃想到,即使使用了encode(‘utf-8’)難道其實內(nèi)存中的編碼格式還是不對?
于是我試著使用codecs將text先存入硬盤,再按照utf-8讀取出來,果然好了.但是很明顯的代碼真的很爛,但是我確實確定了確實是最后輸入wordcloud的文本編碼有問題,最起碼并非真正的可用的utf-8編碼(encode(‘utf-8’)并沒有發(fā)揮作用),于是我試著直接將其替換為python內(nèi)部使用的unicode對象,結(jié)果果然成功了.
生成詞云實例
# - * - coding: utf - 8 -*- # # 作者:田豐(FontTian) # 創(chuàng)建時間:'2017/5/23' # 郵箱:fonttian@163.com # CSDN:http://blog.csdn.net/fontthronefrom os import path from nlpir import * from scipy.misc import imread import matplotlib.pyplot as plt from wordcloud import WordCloud, ImageColorGenerator from ctypes import * import sys reload(sys) sys.setdefaultencoding('utf-8') d = path.dirname(__file__)text_path = 'txt/lztest.txt' # 設(shè)置要分析的文本路徑 stopwords_path = 'stopwords\stopwords1893.txt' # 停用詞詞表 text = open(path.join(d, text_path)).read() txt = seg(text) kw_list = [] seg_list = []# 獲得新詞,第二個參數(shù)控制新詞的個數(shù),排名按照TF-IDF(term frequency–inverse document frequency排序 # 該功能可以和AddUserWord()方法配合使用,以更好地獲取分詞效果# print strs1 # print type(strs1) # 富山雅史/n_new/28.45#白王血裔/n_new/19.83#秘儀咒文/n_new/19.19#風紀委員會主席/n_new/15.30#龍族/n_new/14.48#龍類/n_new/13.79#龍族血裔/n_new/13.78#龍族血統(tǒng)/n_new/13.19#執(zhí)行部/n_new/12.74#白王/n_new/12.68#煉金/n_new/11.75# # <type 'str'>def getNewWordsByNLPIR(text, number):txt1 = GetNewWords(text, c_int(number), [c_char_p, c_int, c_bool])txt2 = txt1.split('#')txt3 = []txt4 = []txt5 = []for item2 in txt2:txt3.append(item2.encode('utf-8').split('/'))if txt3 != []:txt4.append(txt3)txt3 = []for i in txt4:for j in i:if j[0] != [] and j[0] != '':txt5.append(j[0])return txt5strs1 = getNewWordsByNLPIR(text, 10) for i in strs1:print ifor t in txt:seg_list.append(t[0].encode('utf-8'))# 去除停用詞 def NLPIRclearText(seg_list):mywordlist = []liststr = "/ ".join(seg_list)f_stop = open(stopwords_path)try:f_stop_text = f_stop.read()f_stop_text = unicode(f_stop_text, 'utf-8')finally:f_stop.close()f_stop_seg_list = f_stop_text.split('\n')for myword in liststr.split('/'):if not (myword.strip() in f_stop_seg_list) and len(myword.strip()) > 1:mywordlist.append(myword)return ''.join(mywordlist)# 去除完停用詞的文本 strs = NLPIRclearText(seg_list) # print s font_path = r'C:\Windows\Fonts\simfang.ttf' # 為worldcloud設(shè)置中文字體路徑?jīng)]# 設(shè)置詞云屬性 wc = WordCloud(font_path=font_path, # 設(shè)置字體background_color="white", # 背景顏色max_words=200, # 詞云顯示的最大詞數(shù)max_font_size=100, # 字體最大值random_state=42,width=1000, height=860, margin=2, # 設(shè)置圖片默認的大小,但是如果使用背景圖片的話,那么保存的圖片大小將會)# 因為NLPIR在處理中文時,會自動修改文本編碼,所以在使用worldcloud時需要修改文本編碼 # 否則會造成:無法在wordcloud中顯示NLPIR分詞后的漢語詞語,而只能顯示其中的英文wc.generate(unicode(strs, encoding='utf8'))plt.imshow(wc) plt.axis("off") plt.show()wc.to_file('test001.png')總結(jié)
以上是生活随笔為你收集整理的Python NLPIR2016 与 wordcloud 结合生成中文词云的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 源码:我的关于NLP的博客(持续更新中.
- 下一篇: Python 任意中文文本生成词云 最终