1. 程式人生 > 其它 >python詞雲

python詞雲

四行Python程式碼上手詞雲製作

1號詞雲:《葛底斯堡演說》黑色背景詞雲(4行程式碼上手)

import wordcloud
w = wordcloud.WordCloud()
w.generate('and that government of the people, by the people, for the people, shall not perish from the earth.')
w.to_file('output1.png')

執行完成之後,在程式碼所在的資料夾,就會出現output.png圖片檔案。可以看出,wordcloud自動將and that by the not from

等廢話片語過濾掉,並且把出現次數最多的people大號顯示。

# 1號詞雲:葛底斯堡演說黑色背景詞雲
# B站專欄:同濟子豪兄 2019-5-23
# 匯入詞雲製作第三方庫wordcloud
import wordcloud
# 建立詞雲物件,賦值給w,現在w就表示了一個詞雲物件
w = wordcloud.WordCloud()

# 呼叫詞雲物件的generate方法,將文字傳入
w.generate('and that government of the people, by the people, for the people, shall not perish from the earth.
') # 將生成的詞雲儲存為output1.png圖片檔案,儲存出到當前資料夾中 w.to_file('output1.png')

wordcloud庫為每一個詞雲生成一個WordCloud物件(注意,此處的W和C是大寫)

也就是說,wordcloud.WordCloud()代表一個詞雲物件,我們將它賦值給w

現在,這個w就是詞雲物件啦!我們可以呼叫這個物件。

我們可以在WordCloud()括號裡填入各種引數,控制詞雲的字型、字號、字的顏色、背景顏色等等。

wordcloud庫會非常智慧地按空格進行分詞及詞頻統計,出現次數多的詞就大。