前叙
利用下面的代碼你将可以将任意中文文本生成詞雲,其分詞部分由jieba,NLPIR2016兩個部分組成,生成詞語由worldcloud負責,預設會自動發現文本中的20個新詞并添加到詞庫中,當然你也可以手動添加或者通過txt添加使用者詞庫.code中已經有十分詳細的設定說明與代碼解釋,如果你想進一步學習其詳細内容,你可以參考我在第二部分提供的部落格清單
想要進一步學習使用的參考部落格清單
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(中科院漢語分詞系統)的使用 十五分鐘快速入門與完全掌握:http://blog.csdn.net/fontthrone/article/details/72885372
Python NLPIR2016 與 wordcloud 結合生成中文詞雲:http://blog.csdn.net/fontthrone/article/details/72987154
相關代碼下載下傳:http://blog.csdn.net/fontthrone/article/details/72885329
source code
# - * - coding: utf - 8 -*-
#
# 作者:田豐(FontTian)
# 建立時間:'2017/5/23'
# 郵箱:[email protected]
# 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")
# 添加使用者詞庫為主詞典,原詞典變為非主詞典
# ImportUserDict('userdic.txt')
# 為NLPIR2016 添加使用者詞典
from wordcloud import WordCloud, ImageColorGenerator
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# 擷取目前檔案路徑
# __file__ 為目前檔案, 在ide中運作此行會報錯,可改為
# d = path.dirname('.')
d = path.dirname(__file__)
stopwords = {}
isCN = # 預設啟用中文分詞
isJieba = # 預設使用NLPIR2016進行分詞
isGetNewWords = # 預設使用NLPIR擷取新詞
number = # 在使用NLPIR 時候預設自動擷取的新詞
back_coloring_path = "img/lz1.jpg" # 設定背景圖檔路徑
text_path = 'txt/lztest.txt' # 設定要分析的文本路徑
font_path = 'D:\Fonts\simkai.ttf' # 為worldcloud設定中文字型路徑沒
stopwords_path = 'stopwords\stopwords1893.txt' # 停用詞詞表
imgname1 = "WordCloudDefautColors.png" # 儲存的圖檔名字1(隻按照背景圖檔形狀)
imgname2 = "WordCloudColorsByImg.png" # 儲存的圖檔名字2(顔色按照背景圖檔顔色布局生成)
my_words_list = ['路明非'] # 在結巴的詞庫中添加新詞
back_coloring = imread(path.join(d, back_coloring_path)) # 設定背景圖檔
# 設定詞雲屬性
wc = WordCloud(font_path=font_path, # 設定字型
background_color="white", # 背景顔色
max_words=, # 詞雲顯示的最大詞數
mask=back_coloring, # 設定背景圖檔
max_font_size=, # 字型最大值
random_state=,
width=, height=, margin=, # 設定圖檔預設的大小,但是如果使用背景圖檔的話,那麼儲存的圖檔大小将會
)
# 使用NLPIR 自動發現新詞
def add_word(text, number):
strs1 = getNewWordsByNLPIR(text, number)
if isJieba == :
if isGetNewWords == :
for i in strs1:
AddUserWord(i)
for i in my_words_list:
AddUserWord(i)
else:
if isGetNewWords == :
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()) > :
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[] != [] and j[] != '':
txt5.append(j[])
return txt5
# 使用NLPIR2016 進行分詞
def useNLPIR2016(text):
txt = seg(text)
seg_list = []
for t in txt:
seg_list.append(t[].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()) > :
mywordlist.append(myword)
return ''.join(mywordlist)
# 如果使用中文分詞的話
if isCN == :
add_word(text, number)
if isJieba == :
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函數
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))