词云 (Word Cloud)是对文本中出现频率较高的词语给予视觉化展现的图形, 是一种常见的文本挖掘的方法。目前已有多种数据分析工具支持这种图形,如Matlab, SPSS, SAS, R 和 Python 等等,也有不少在线网页能生成 word cloud, 例如wordclouds.comhtml
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。
dom
在使用 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.
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 这种图形的精髓。