当前位置: 移动技术网 > IT编程>脚本编程>Python > Word Cloud - Python

Word Cloud - Python

2019年06月04日  | 移动技术网IT编程  | 我要评论

奇奇漂流记,茂名传销,美眉草莓糕

what's word cloud

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

word cloud example

create word cloud via python

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

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.



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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网