Python 任意中文文本生成词云 最终版本
前敘
利用下面的代碼你將可以將任意中文文本生成詞云,其分詞部分由jieba,NLPIR2016兩個部分組成,生成詞語由worldcloud負責,默認會自動發(fā)現(xiàn)文本中的20個新詞并添加到詞庫中,當然你也可以手動添加或者通過txt添加用戶詞庫.code中已經(jīng)有十分詳細的設(shè)置說明與代碼解釋,如果你想進一步學(xué)習(xí)其詳細內(nèi)容,你可以參考我在第二部分提供的博客列表
想要進一步學(xué)習(xí)使用的參考博客列表
Python詞云 wordcloud 十五分鐘入門與進階:http://blog.csdn.net/fontthrone/article/details/72775865
Python中文分詞 jieba 十五分鐘入門與進階:http://blog.csdn.net/fontthrone/article/details/72782499
Python 中文分詞 NLPIR 快速搭建:http://blog.csdn.net/fontthrone/article/details/72872413
Python NLPIR(中科院漢語分詞系統(tǒng))的使用 十五分鐘快速入門與完全掌握:http://blog.csdn.net/fontthrone/article/details/72885372
Python NLPIR2016 與 wordcloud 結(jié)合生成中文詞云:http://blog.csdn.net/fontthrone/article/details/72987154
相關(guān)代碼下載:http://blog.csdn.net/fontthrone/article/details/72885329
source code
# - * - coding: utf - 8 -*- # # 作者:田豐(FontTian) # 創(chuàng)建時間:'2017/5/23' # 郵箱:fonttian@163.com # CSDN:http://blog.csdn.net/fontthrone from os import path from scipy.misc import imread import matplotlib.pyplot as plt import jieba from nlpir import * from ctypes import * # jieba.load_userdict("txt\userdict.txt") # 添加用戶詞庫為主詞典,原詞典變?yōu)榉侵髟~典 # ImportUserDict('userdic.txt') # 為NLPIR2016 添加用戶詞典 from wordcloud import WordCloud, ImageColorGenerator import sysreload(sys) sys.setdefaultencoding('utf-8')# 獲取當前文件路徑 # __file__ 為當前文件, 在ide中運行此行會報錯,可改為 # d = path.dirname('.') d = path.dirname(__file__)stopwords = {} isCN = 1 # 默認啟用中文分詞 isJieba = 0 # 默認使用NLPIR2016進行分詞 isGetNewWords = 1 # 默認使用NLPIR獲取新詞 number = 20 # 在使用NLPIR 時候默認自動獲取的新詞 back_coloring_path = "img/lz1.jpg" # 設(shè)置背景圖片路徑 text_path = 'txt/lztest.txt' # 設(shè)置要分析的文本路徑 font_path = 'D:\Fonts\simkai.ttf' # 為worldcloud設(shè)置中文字體路徑?jīng)] stopwords_path = 'stopwords\stopwords1893.txt' # 停用詞詞表 imgname1 = "WordCloudDefautColors.png" # 保存的圖片名字1(只按照背景圖片形狀) imgname2 = "WordCloudColorsByImg.png" # 保存的圖片名字2(顏色按照背景圖片顏色布局生成)my_words_list = ['路明非'] # 在結(jié)巴的詞庫中添加新詞back_coloring = imread(path.join(d, back_coloring_path)) # 設(shè)置背景圖片# 設(shè)置詞云屬性 wc = WordCloud(font_path=font_path, # 設(shè)置字體background_color="white", # 背景顏色max_words=2000, # 詞云顯示的最大詞數(shù)mask=back_coloring, # 設(shè)置背景圖片max_font_size=100, # 字體最大值random_state=42,width=1000, height=860, margin=2, # 設(shè)置圖片默認的大小,但是如果使用背景圖片的話,那么保存的圖片大小將會)# 使用NLPIR 自動發(fā)現(xiàn)新詞 def add_word(text, number):strs1 = getNewWordsByNLPIR(text, number)if isJieba == 0:if isGetNewWords == 1:for i in strs1:AddUserWord(i)for i in my_words_list:AddUserWord(i)else:if isGetNewWords == 1:for i in strs1:jieba.add_word(i)for i in my_words_list:jieba.add_word(i)text = open(path.join(d, text_path)).read()# 使用 jieba 清理停用詞 def jiebaclearText(text):mywordlist = []seg_list = jieba.cut(text, cut_all=False)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)# 使用NLPIR 獲取新詞 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# 使用NLPIR2016 進行分詞 def useNLPIR2016(text):txt = seg(text)seg_list = []for t in txt:seg_list.append(t[0].encode('utf-8'))return seg_list# 去除停用詞 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)# 如果使用中文分詞的話 if isCN == 1:add_word(text, number)if isJieba == 0:seg_list = useNLPIR2016(text)text = NLPIRclearText(seg_list)text = unicode(text, encoding='utf8')else:add_word(my_words_list)text = jiebaclearText(text)# 生成詞云, 可以用generate輸入全部文本(wordcloud對中文分詞支持不好,建議啟用中文分詞),也可以我們計算好詞頻后使用generate_from_frequencies函數(shù) wc.generate(text) print text # wc.generate_from_frequencies(txt_freq) # txt_freq例子為[('詞a', 100),('詞b', 90),('詞c', 80)] # 從背景圖片生成顏色值 image_colors = ImageColorGenerator(back_coloring)plt.figure() # 以下代碼顯示圖片 plt.imshow(wc) plt.axis("off") plt.show() # 繪制詞云# 保存圖片 wc.to_file(path.join(d, imgname1))image_colors = ImageColorGenerator(back_coloring)plt.imshow(wc.recolor(color_func=image_colors)) plt.axis("off") # 繪制背景圖片為顏色的圖片 plt.figure() plt.imshow(back_coloring, cmap=plt.cm.gray) plt.axis("off") plt.show() # 保存圖片 wc.to_file(path.join(d, imgname2))總結(jié)
以上是生活随笔為你收集整理的Python 任意中文文本生成词云 最终版本的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python NLPIR2016 与 w
- 下一篇: Python运行异常 Original