1. 程式人生 > >Python基於jieba的中文詞雲

Python基於jieba的中文詞雲

今日學習了python的詞雲技術

from os import path
from wordcloud import WordCloud
import matplotlib.pyplot as plt

d=path.dirname(__file__)
text=open(path.join(d,"data//constitution.txt")).read()

# 步驟3-2:設定一張詞雲圖物件
wordcloud = WordCloud(background_color="white", max_font_size=40).generate(text)

# 步驟4-1:建立一個圖表畫布
plt.figure()
# 步驟4-2:設定圖片
plt.imshow(wordcloud, interpolation="bilinear")
# 步驟4-3:取消圖表x、y軸
plt.axis("off")
# 顯示圖片
plt.show()

結果如下:這是沒有背景圖的詞雲

接下來這個是愛麗絲漫遊小說的詞雲

from os import path
from PIL import Image
import numpy as np
from wordcloud import WordCloud
import matplotlib.pyplot as plt

d=path.dirname(__file__)
text=open(path.join(d,"data//alice.txt")).read()
alice_mask = np.array(Image.open(path.join(d, "data/alice_mask.png")))

wordcloud=WordCloud(background_color="white",max_words=2000,mask=alice_mask)
wordcloud.generate(text)

wordcloud.to_file(path.join(d,"images//alice_word.png"))

用英文做詞雲很簡單,不需要很麻煩的分詞技術,用wordcloud模組就可以簡單實現

執行結果如下

背景圖:

最後是中文詞雲,中文詞雲就比較麻煩了,得用到jieba模組的分詞技術,還得篩選

import jieba
from os import path  #用來獲取文件的路徑

#詞雲
from PIL import Image
import numpy as  np
import matplotlib.pyplot as plt
#詞雲生成工具
from wordcloud import WordCloud,ImageColorGenerator
#需要對中文進行處理
import matplotlib.font_manager as fm

#背景圖
bg=np.array(Image.open("data/4.jpg"))

#獲取當前的專案檔案加的路徑
d=path.dirname(__file__)
#讀取停用詞表
stopwords_path='data/alice.txt'
#新增需要自定以的分詞
jieba.add_word("侯亮平")


#讀取要分析的文字
text_path="data//sanguo.txt"
#讀取要分析的文字,讀取格式
text=open(path.join(d,text_path),encoding="utf8").read()

#定義個函式式用於分詞
def jiebaclearText(text):
    #定義一個空的列表,將去除的停用詞的分詞儲存
    mywordList=[]
    #進行分詞
    seg_list=jieba.cut(text,cut_all=False)
    #將一個generator的內容用/連線
    listStr='/'.join(seg_list)
    #開啟停用詞表
    f_stop=open(stopwords_path,encoding="utf8")
    #讀取
    try:
        f_stop_text=f_stop.read()
    finally:
        f_stop.close()#關閉資源
    #將停用詞格式化,用\n分開,返回一個列表
    f_stop_seg_list=f_stop_text.split("\n")
    #對預設模式分詞的進行遍歷,去除停用詞
    for myword in listStr.split('/'):
        #去除停用詞
        if not(myword.split()) in f_stop_seg_list and len(myword.strip())>1:
            mywordList.append(myword)
    return ' '.join(mywordList)
text1=jiebaclearText(text)

#生成
wc=WordCloud(
    background_color="white",
    max_words=150,
    mask=bg,            #設定圖片的背景
    max_font_size=60,
    random_state=42,
    font_path='C:/Windows/Fonts/simkai.ttf'   #中文處理,用系統自帶的字型
    ).generate(text1)
#為圖片設定字型
my_font=fm.FontProperties(fname='C:/Windows/Fonts/simkai.ttf')
#產生背景圖片,基於彩色影象的顏色生成器
image_colors=ImageColorGenerator(bg)
#開始畫圖
plt.imshow(wc,interpolation="bilinear")
#為雲圖去掉座標軸
plt.axis("off")
#畫雲圖,顯示
#plt.figure()
plt.show()
#為背景圖去掉座標軸
plt.axis("off")
plt.imshow(bg,cmap=plt.cm.gray)
#plt.show()

#儲存雲圖
wc.to_file("data/sanguo.png")

執行結果:

可以看出,三國前20回裡,呂布,曹操,玄德等詞出現的最多