What's Word Cloud

词云 (Word Cloud)是对文本中出现频率较高的词语给予视觉化展示的图形, 是一种常见的文本挖掘的方法。目前已有多种数据分析工具支持这种图形,如Matlab, SPSS, SAS, R 和 Python 等等,也有很多在线网页能生成 word cloud, 例如wordclouds.com

Word Cloud Example

Create Word Cloud via Python

Python 可以使用 wordcloud 模块来生成词云。

1) 安装 wordcloud, matplotlib 及其依赖模块。

2) 准备文本。

我从维基百科中找到一段关于 Word Cloud History 的文字,以下将以这段文字为例。复制这段文字到 NotePad,并将其保存为 .*txt 文本格式。

3) 运行 Python script。

"""
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 Python

Notes

在使用 wordcloud 模块的时候曾发现某些词语的频率(或者权重)是一样的,但是在生成的图形中字体大小却不一样。

Google 后找到开发作者的回答:

wordcloud document


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

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!