1. 程式人生 > 其它 >[社團課L1] 資料視覺化——詞雲

[社團課L1] 資料視覺化——詞雲

詞雲是文字大資料視覺化的重要方式,可以將大段文字中的關鍵語句和詞彙高亮展示。

以上為用福建師大附中的百度百科詞條文字做的詞雲;

一.下載第三方庫:wordcloud


pip install wordcloud

二.最簡單的四行詞雲

  • 詞雲1:《肖申克的救贖》:Hope is a good thing, maybe the best of things and no good thing ever dies!
import wordcloud

w = wordcloud.WordCloud() #建立wordcloud物件
w.generate('Hope is a good thing, maybe the best of things and no good thing ever dies! ')
w.to_file('output1.png') #把完成的詞雲圖片儲存為output1.png檔案

執行程式碼,可在程式碼儲存的資料夾下找到名為output1.png的圖片,即為上圖;
可以發現WordCloud並不會用上所有字元,它會選出重要的詞,並按出現次數多少來設定字型的大小,隨機放置成一張詞雲;

三.新增引數


  • 詞雲2:詞雲1的升級版
import wordcloud

w = wordcloud.WordCloud(width = 1000,
                        height = 700,
                        background_color = 'white')
w.generate('Hope is a good thing, maybe the best of things and no good thing ever dies!')
w.to_file('output2.png')

在建立wordcloud物件時,增加了一些引數,例如widthheight高,和background_color背景顏色。
執行結果如下:

更多常見引數:

  • width 詞雲圖片寬度,預設400畫素;

  • height 詞雲圖片高度,預設200畫素;

  • background_color 詞雲圖片的背景顏色,預設為黑色,傳入‘’包圍的顏色英語單詞;

  • font_step 字號增大的梯度,預設1號;

  • font_path 指定字型路徑,預設None,如若詞雲中出現中文則需加上font_path = 'msyh.ttc'

  • mini_font_size 最小字號,預設4號;

  • max_font_size 最大字號,根據高度自動調節;

  • max_words 最大詞數,預設200;

  • stop_words 不顯示的單詞,如需遮蔽多個單詞,可寫為stop_words={'dog','cat'};

  • Scale 清晰度,預設值1,值越大,影象密度越大越清晰;

  • mask 指定詞雲形狀圖片,預設為矩形;

  • 詞雲3:福建師大附中百度百科詞條
    顯然百度百科詞條文字非常長,直接放在程式碼中很不方便;先把詞條文字複製到檔案ansfun.txt中,而後在程式中從檔案中讀取文字;

import wordcloud

w = wordcloud.WordCloud(background_color='white',
                        max_font_size=50,
                        scale=15,
                        font_path='msyh.ttc')
f = open('ansfun.txt',encoding='utf-8')
#txt檔案中的內容為中文,需要加上encoding='utf-8'
txt = f.read()
w.generate(txt)
w.to_file('output3.png')

四.加入詞雲形狀


  • 詞雲4:圓形的福建師大附中百度百科詞條
    首先下載第三方庫imageio:
pip install imageio

通過以下程式碼讀入外部圖片形狀:

import wordcloud
import imageio

ma=imageio.imread('circle.jfif') #選用名為circle.jfif的圖片作為詞雲形狀
w = wordcloud.WordCloud(background_color = 'white',
                        max_font_size = 50,
                        scale = 15, #不加此引數得出的詞雲較模糊
                        mask = ma, #把提取的圖片設為mask引數
                        font_path = 'msyh.ttc')
imagecol=wordcloud.ImageColorGenerator(ma)
f = open('ansfun.txt',encoding='utf-8')
txt = f.read()
w.generate(txt)
w.to_file('output4.png')

選擇圖片時儘量使用白底圖片;

五.按模板著色


import wordcloud
import imageio

ma = imageio.imread('circle.jfif')
w = wordcloud.WordCloud(background_color = 'white',
                        max_font_size = 50,
                        scale = 15,
                        mask = ma,
                        font_path = 'msyh.ttc')
imagecol = wordcloud.ImageColorGenerator(ma)
f = open('ansfun.txt',encoding='utf-8')
txt = f.read()
w.generate(txt)
w_col = w.recolor(color_func = imagecol)
w_col.to_file('output5.png')