Word Cloud (詞雲) - Python


>>What's Word Cloud

詞雲 (Word Cloud)是對文本中出現頻率較高的詞語給予視覺化展現的圖形, 是一種常見的文本挖掘的方法。目前已有多種數據分析工具支持這種圖形,如Matlab, SPSS, SAS, R 和 Python 等等,也有不少在線網頁能生成 word cloud, 例如wordclouds.comhtml

Word Cloud Example


>> Create Word Cloud via Python

Python 能夠使用 wordcloud 模塊來生成詞雲。python

1) 安裝 wordcloud, matplotlib 及其依賴模塊。git

2) 準備文本。github

我從維基百科中找到一段關於 Word Cloud History 的文字,如下將以這段文字爲例。複製這段文字到 NotePad,並將其保存爲 .*txt 文本格式。算法

3) 運行 Python script。canvas

"""
Python Example
===============
Generating a wordcloud from the txt file using Python.
"""

from wordcloud import WordCloud

# Read the whole text from txt.
fp = "C:/Users/yuki/Desktop/WordCloudHistory.txt"
text = open(fp).read()

# Generate a word cloud image
wordcloud = WordCloud(
font_path = "C:/Windows/Fonts/BROADW.TTF", 
width = 600, #width of the canvas.
height = 400, #height of the canvas.
max_font_size = 60,
font_step = 1,
background_color = "white",
random_state = 1,
margin = 2,
colormap = "tab20" #matplotlib colormap
).generate(text)

# Display the generated image in matplotlib way:
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

4) 生成 word cloud。
Word Cloud Pythondom


>> Notes

在使用 wordcloud 模塊的時候曾發現某些詞語的頻率(或者權重)是同樣的,可是在生成的圖形中字體大小卻不同。工具

Google 後找到開發做者的回答:字體

wordcloud document
code


The algorithm might give more weight to the ranking of the words than their actual frequencies, depending on the max_font_size and the scaling heuristic.

github issues


The scaling is relative to the size of the figure and the frequency of the words. The frequencies are normalized against the max frequency, so the absolute values are irrelevant.

大概是爲了將詞語儘量地填滿畫布,wordcloud 算法會自動根據 max_font_size 和 scale 自動調整詞語的權重。那麼 wordcloud 生成的圖形詞語大小和他的詞頻(或者權重)的絕對值並非一一對應的關係。

我以爲嘛:雖然這樣畫出的圖形比較好看,但仍是以爲有點奇怪,畢竟按詞頻大小展現詞語應該是 word cloud 這種圖形的精髓。


>> Sample Code

download here


  1. Word Cloud (詞雲) - JavaScript
  2. Word Cloud (詞雲) - R
  3. Word Cloud (詞雲) - Matlab
相關文章
相關標籤/搜索