1. 程式人生 > >生成詞雲之python中WordCloud包的用法

生成詞雲之python中WordCloud包的用法

效果圖:
詞雲圖

這是python中使用wordcloud包生成的詞雲圖。

下面來介紹一下wordcloud包的基本用法。

class wordcloud.WordCloud(font_path=None, width=400, height=200, margin=2, ranks_only=None, prefer_horizontal=0.9,mask=None, scale=1, color_func=None, max_words=200, min_font_size=4, stopwords=None, random_state=None,background_color='black', max_font_size
=None, font_step=1, mode='RGB', relative_scaling=0.5, regexp=None, collocations=True,colormap=None, normalize_plurals=True)

這是wordcloud的所有引數,下面具體介紹一下各個引數:

font_path : string //字型路徑,需要展現什麼字型就把該字型路徑+字尾名寫上,如:font_path = '黑體.ttf'

width : int (default=400) //輸出的畫布寬度,預設為400畫素

height : int (default=200) //輸出的畫布高度,預設為200畫素
prefer_horizontal : float (default=0.90) //詞語水平方向排版出現的頻率,預設 0.9 (所以詞語垂直方向排版出現頻率為 0.1 ) mask : nd-array or None (default=None) //如果引數為空,則使用二維遮罩繪製詞雲。如果 mask 非空,設定的寬高值將被忽略,遮罩形狀被 mask 取代。除全白(#FFFFFF)的部分將不會繪製,其餘部分會用於繪製詞雲。如:bg_pic = imread('讀取一張圖片.png'),背景圖片的畫布一定要設定為白色(#FFFFFF),然後顯示的形狀為不是白色的其他顏色。可以用ps工具將自己要顯示的形狀複製到一個純白色的畫布上再儲存,就ok了。
scale : float (default=1) //按照比例進行放大畫布,如設定為1.5,則長和寬都是原來畫布的1.5倍。 min_font_size : int (default=4) //顯示的最小的字型大小 font_step : int (default=1) //字型步長,如果步長大於1,會加快運算但是可能導致結果出現較大的誤差。 max_words : number (default=200) //要顯示的詞的最大個數 stopwords : set of strings or None //設定需要遮蔽的詞,如果為空,則使用內建的STOPWORDS background_color : color value (default=”black”) //背景顏色,如background_color='white',背景顏色為白色。 max_font_size : int or None (default=None) //顯示的最大的字型大小 mode : string (default=”RGB”) //當引數為“RGBA”並且background_color不為空時,背景為透明。 relative_scaling : float (default=.5) //詞頻和字型大小的關聯性 color_func : callable, default=None //生成新顏色的函式,如果為空,則使用 self.color_func regexp : string or None (optional) //使用正則表示式分隔輸入的文字 collocations : bool, default=True //是否包括兩個詞的搭配 colormap : string or matplotlib colormap, default=”viridis” //給每個單詞隨機分配顏色,若指定color_func,則忽略該方法。 fit_words(frequencies) //根據詞頻生成詞雲 generate(text) //根據文字生成詞雲 generate_from_frequencies(frequencies[, ...]) //根據詞頻生成詞雲 generate_from_text(text) //根據文字生成詞雲 process_text(text) //將長文字分詞並去除遮蔽詞(此處指英語,中文分詞還是需要自己用別的庫先行實現,使用上面的 fit_words(frequencies) ) recolor([random_state, color_func, colormap]) //對現有輸出重新著色。重新上色會比重新生成整個詞雲快很多。 to_array() //轉化為 numpy array to_file(filename) //輸出到檔案

例子:
想要生成的詞雲的形狀:
詞雲形狀
圖中黑色部分就是詞雲的將要顯示的部分,白色部分不顯示任何詞。

下面是一個文字文件:

How the Word Cloud Generator Works

The layout algorithm for positioning words without overlap is available on GitHub under an open source license as d3-cloud. Note that this is the only the layout algorithm and any code for converting text into words and rendering the final output requires additional development.

As word placement can be quite slow for more than a few hundred words, the layout algorithm can be run asynchronously, with a configurable time step size. This makes it possible to animate words as they are placed without stuttering. It is recommended to always use a time step even without animations as it prevents the browser’s event loop from blocking while placing the words.

The layout algorithm itself is incredibly simple. For each word, starting with the most “important”:

Attempt to place the word at some starting point: usually near the middle, or somewhere on a central horizontal line.
If the word intersects with any previously placed words, move it one step along an increasing spiral. Repeat until no intersections are found.
The hard part is making it perform efficiently! According to Jonathan Feinberg, Wordle uses a combination of hierarchical bounding boxes and quadtrees to achieve reasonable speeds.

Glyphs in JavaScript

There isn’t a way to retrieve precise glyph shapes via the DOM, except perhaps for SVG fonts. Instead, we draw each word to a hidden canvas element, and retrieve the pixel data.

Retrieving the pixel data separately for each word is expensive, so we draw as many words as possible and then retrieve their pixels in a batch operation.

Sprites and Masks

My initial implementation performed collision detection using sprite masks. Once a word is placed, it doesn't move, so we can copy it to the appropriate position in a larger sprite representing the whole placement area.

The advantage of this is that collision detection only involves comparing a candidate sprite with the relevant area of this larger sprite, rather than comparing with each previous word separately.

Somewhat surprisingly, a simple low-level hack made a tremendous difference: when constructing the sprite I compressed blocks of 32 1-bit pixels into 32-bit integers, thus reducing the number of checks (and memory) by 32 times.

In fact, this turned out to beat my hierarchical bounding box with quadtree implementation on everything I tried it on (even very large areas and font sizes). I think this is primarily because the sprite version only needs to perform a single collision test per candidate area, whereas the bounding box version has to compare with every other previously placed word that overlaps slightly with the candidate area.

Another possibility would be to merge a word’s tree with a single large tree once it is placed. I think this operation would be fairly expensive though compared with the analagous sprite mask operation, which is essentially ORing a whole block. 

從這個文字中生成一個詞雲,程式碼如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#coding=utf-8

#匯入wordcloud模組和matplotlib模組
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from scipy.misc import imread


#讀取一個txt檔案

text = open('test.txt','r').read()

#讀入背景圖片

bg_pic = imread('3.png')

#生成詞雲

wordcloud = WordCloud(mask=bg_pic,background_color='white',scale=1.5).generate(text)

image_colors = ImageColorGenerator(bg_pic)
#顯示詞雲圖片

plt.imshow(wordcloud)
plt.axis('off')
plt.show()


#儲存圖片

wordcloud.to_file('test.jpg')

執行結果:
最終生成的詞雲圖

相關推薦

生成pythonWordCloud用法

效果圖: 這是python中使用wordcloud包生成的詞雲圖。 下面來介紹一下wordcloud包的基本用法。 class wordcloud.WordCloud(font_path=None, width=400, height=200, m

已知詞頻生成雲圖(資料庫到生成)--generate_from_frequencies(WordCloud

詞雲圖是根據詞出現的頻率生成詞雲,詞的字型大小表現了其頻率大小。   寫在前面: 用wc.generate(text)直接生成詞頻的方法使用很多,所以不再贅述。 但是對於根據generate_from_frequencies()給定詞頻如何畫詞雲圖的資料找了很久,下面只講這種方法。 gen

python json 用法簡單總結

JSON包的引用 在檔案頭部引用json包 import json python物件與JSON物件的互相轉換 json物件的型別為’str’: dic = {'b':'I', 'a':123, 'c':'100'} j1

Python小程式——利用wordcloud生成(二)

wordcloud庫利用wordcloud物件生成詞雲,其中可以配置很多屬性,讓你的詞雲更加個性化。 w_cloud = wordcloud.WordCloud( font_path=font, background_color=None, mode="RGBA", # 背

Python小程式——利用wordcloud生成(一)

最近自學Python的中文處理,其中用到了wordcloud庫生成一篇文章的詞雲,能更直觀的表現出文章的主題,是一個不錯的工具。雖然現在網上有很多詞雲線上生成的應用,不過為了更個性化一點,還是寫一個自己的詞雲生成工具吧。 import jieba import wordcloud from

python 微信生成(itchat,jieba,wordcloud)

完整程式碼: import itchat import re#正則匹配 # 先登入,掃二維碼登入微信 itchat.login() #獲取好友列表,返回的是json資訊 friends = itchat.get_friends(update=True)[0:] #列印好

利用PythonWordCloud生成

python程式碼: from wordcloud import WordCloud,ImageColorGenerator import matplotlib.pyplot as plt from scipy.misc import imread #載入圖片 #讀

使用Python統計文件詞頻,並且生成

pla sha white acs wid textarea 文章 sid atp .title { text-align: center } .todo { font-family: monospace; color: red } .done { color: green

python生成

cloud arr 文本 [0 mas func word .text ges 期末復習比較忙過段時間來專門寫scrapy框架使用,今天介紹如何用python生成詞雲,雖然網上有很多詞雲生成工具,不過自己用python來寫是不是更有成就感。 今天要生成的是勵誌歌曲的詞雲,百

python爬取微博數據並生成

font 意思 extra 很多 返回 json 自己 技術分享 pre 很早之前寫過一篇怎麽利用微博數據制作詞雲圖片出來,之前的寫得不完整,而且只能使用自己的數據,現在重新整理了一下,任何的微博數據都可以制作出來,放在今天應該比較應景。 一年一度的虐汪節,是繼續蹲在角落默

Python爬取QQ空間好友說說並生成(超詳細)

near 當前 面數據 請求 range 頁面 blank sleep 點擊 前言 先看效果圖: 思路 1.確認訪問的URL 2.模擬登錄你的QQ號 3.判斷好友空間是否加了權限,切換到說說的frame,爬取當前頁面數據,下拉滾動條,翻頁繼續獲取 爬取的內容寫

利用Python把圖片生成!很秀很裝逼!其實非常簡單,不信你看

前言 今天教大家用wrodcloud模組來生成詞雲,我讀取了一篇小說並生成了詞雲,先看一下效果圖: 效果圖一:     進群:548377875   即可獲取數十套PDF哦! 效果圖二:    

Python實現根據指定圖片生成

效果 生成詞雲前 生成詞雲後 實現 新建imageWordCloud.py 在同級目錄下新建aobama.txt,裡面內容是英文單詞(奧巴馬演講稿) 在同級目錄下放一張照片bg.jpg,根據這張照片來生成詞雲 程式碼帶註釋: from os import

Python獲取微信好友簽名生成

tps targe fan generate lis 制作 dom white print ‘‘‘ pip install wxpy pip install matplotlib # 如果下載超時,就換源下載:pip install -i https://pypi.tu

Python爬取微博資料生成圖片

很早之前寫過一篇怎麼利用微博資料製作詞雲圖片出來,之前的寫得不完整,而且只能使用自己的資料,現在重新整理了一下,任何的微博資料都可以製作出來,放在今天應該比較應景。 一年一度的虐汪節,是繼續蹲在角落默默吃狗糧還是主動出擊告別單身汪加入散狗糧的行列就看你啦,七夕送什麼才有心意,程式猿可以試試用

python爬豆瓣影評&根據詞頻生成

python爬豆瓣影評&根據詞頻生成詞雲通過爬取豆瓣上正在上映的電影影評資訊,並根據評論詞頻生成詞雲。一、需要的包import warnings # 防止出現future warning warnings.filterwarnings("ignore") from

Python生成——WordCount入門

主要內容: 介紹詞雲 用Python的WordCount包實現詞雲 詞雲 關鍵詞的視覺化描述; 圖形視覺化; 用於彙總使用者生成的標籤或一個網站的文字內容; 重要程度能通過改變字型大小或顏色來表現; 大多數標籤本身就是超級連結,直接指向與標籤相聯

python爬取資料熱點生成

這是當時在中國mooc學 用python玩轉資料 時,寫的一個小demo. 程式實現步驟 1.從某一網站爬取資料,比如我是在豆瓣爬取的書評 利用Requests庫的get()爬取網頁 使用BeatifulSoup庫對爬取網頁進行解析。 寫入

Python爬取微博資料生成圖片

很早之前寫過一篇怎麼利用微博資料製作詞雲圖片出來,之前的寫得不完整,而且只能使用自己的資料,現在重新整理了一下,任何人的微博資料都可以製作出來,即使是Python小白也能分分鐘做出來。 準備工作 本環境基於Python3,理論上Python2.7也是可行的,先安裝必要的第三方依賴包: #

Python3網路爬蟲:requests+mongodb+wordcloud 爬取豆瓣影評並生成

Python版本: python3.+ 執行環境: Mac OS IDE: pycharm 一 前言 二 豆瓣網影評爬取 網頁分析 程式碼編寫 三 資料庫實裝 四