目錄python
wordcloud是優秀的詞雲展現第三方庫函數
pip install wordcloud
(cmd命令行)字體
wordcloud庫把詞雲看成一個WordCloud對象ui
w = wordcloud.WordCloud()
命令行
方法 | 描述 |
---|---|
w.generate(txt) | 向WordCloud對象w中加載文本txt,w.generate("Python and WordCloud") |
w.to_file(filename) | 將詞雲輸出爲圖像文件,.png或.jpg?x-oss-process=style/watermark格式,w.to_file("outfile.png") |
import wordcloud w = wordcloud.WordCloud() w.generate("Python and WordCloud") c.to_file("pywordcloud.png")
w = wordcloud.WordCloud(<參數>)
3d
參數 | 描述 |
---|---|
width | 指定詞雲對象生成圖片的寬度,默認400像素 |
height | 指定詞雲對象生成圖片的高度,默認200像素 |
min_font_size | 指定詞雲中字體的最小字號,默認4號 |
max_font_size | 指定詞雲中字體的最大字號,根據高度自動調節 |
font_step | 指定詞雲中字體字號的步進間隔,默認爲1 |
font_path | 指定字體文件的路徑,默認None |
max_words | 指定詞雲顯示的最大單詞數量,默認200 |
stop_words | 指定詞雲的排除詞列表,即不顯示的單詞列表 |
mask | 指定詞雲形狀,默認爲長方形,須要引用imread()函數 |
background_color | 指定詞雲圖片的背景顏色,默認爲黑色 |
# mask from imageio import imread mk=imread("pic.png") w=wordcloud.WordCloud(mask=mk)
import wordcloud txt = "life is short, you need python" w = wordcloud.WordCloud(background_color="white") w.generate(txt) w.to_file("pywcloud.png")
中文須要先分詞並組成空格分隔字符串code
import jieba import wordcloud txt = "Nick 是上海虹橋最帥的男人,沒有之一,由於他就是最帥的" w = wordcloud.WordCloud( width=1000,\ font_path="/Library/Fonts/Heiti.ttc",height=700) w.generate(" ".join(jieba.lcut(txt))) w.to_file("pywcloud.png")
import jieba import wordcloud txt = "Nick 是上海虹橋最帥的男人,沒有之一,由於他就是最帥的" w = wordcloud.WordCloud( width=1000,\ font_path="/Library/Fonts/Heiti.ttc",height=700) w.generate(" ".join(jieba.lcut(txt))) w.to_file("pywcloud.png")
Building prefix dict from the default dictionary ... Loading model from cache /var/folders/mh/krrg51957cqgl0rhgnwyylvc0000gn/T/jieba.cache Loading model cost 1.047 seconds. Prefix dict has been built succesfully. <wordcloud.wordcloud.WordCloud at 0x1150979e8>