贅婿詞雲圖製作

前言

之前的文章我們已經介紹瞭如何使用wordcloud庫製作中英文詞雲圖,並介紹了中英文停用詞的使用方法,介紹瞭如何美化詞雲圖,例如換字體背景顏色,背景換成圖片等,那這次我們就以現在很火的電視劇贅婿爲例,製作贅婿小說的詞雲圖。

數據準備

  • 贅婿小說txt
  • 停用詞表
  • 一張贅婿相關背景圖

製作流程

  • 讀取小說文本
  • 利用jieba庫對文本進行分詞
  • 設置停用詞表
  • 利用wordcloud庫製作詞雲圖

代碼

根據上面的流程,編寫代碼。

from matplotlib import pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
import jieba

fp = open('贅婿.txt','r')
text = fp.read()
cut_word = " ".join(jieba.cut(text))

stopwords = set()
content = [line.strip() for line in open('hit_stopwords.txt','r').readlines()]
stopwords.update(content)

background_image = plt.imread('贅婿.jpg')

wc = WordCloud(background_color = 'white',
               font_path = r'/System/Library/Fonts/Supplemental/Songti.ttc',
               stopwords = stopwords,
               mask = background_image,
               max_words=2000)
wc.generate(cut_word)

#改變字體顏色
img_colors = ImageColorGenerator(background_image)
#字體顏色爲背景圖片的顏色
wc.recolor(color_func=img_colors)

plt.imshow(wc, interpolation='bilinear')
plt.axis('off') #取消座標軸
plt.show()

詞雲圖可以看出,還是有很多次我們還需要過濾掉,這部分內容在jieba庫的使用中再進行講解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章