143、python中使用wordcloud包生成词云图

一、Python的wordcloud包在anaconda中安装

  1. 根据自己的电脑系统及安装的anaconda版本下载对应wordcloud安装包。

window环境下载地址:<u>http://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud</u>

1.png

我自己电脑是win7 64位系统,安装anaconda3,我下载的是:
2.png

然后把下载到的文件放在所执行的目录文件下。

  1. 使用pip安装

在终端Anaconda Prompt打开之后:你得先进入这个.whl文件所在的位置,我是放在了C:\notebook文件夹下面,具体你去找自己下载放到了那里!!

输入:pip install wordcloud-1.4.1-cp36-cp36m-win_amd64.whl

二、使用wordcloud包生成词云图

我是参考下面这篇博客来制作词云图,里面有详细介绍wordcloud包的用法

链接:<u>http://blog.csdn.net/u010309756/article/details/67637930</u>

下面是一个要分析的文本文档内容:

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.

下面是代码实现部分:

先导入相关包:
3.导入相关包.png

(1)使用背景图片制作词云图片

我使用的背景图片如下:
4.love.jpg

生成词云图:
5.png
6.生成词云图.png

(2)不使用背景图片:
7.不使用背景图片.png

源码:


# coding: utf-8

# # python中使用wordcloud包生成词云图

# 我是参考下面这篇博客来制作词云图,里面有详细介绍wordcloud包的用法

#

# 链接:[生成词云之python中WordCloud包的用法](https://blog.csdn.net/u010309756/article/details/67637930)

# 下面是一个要分析的文本文档内容:

#

# 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.

# ### 下面是代码实现部分

# In[1]:

#导入wordcloud模块和matplotlib模块

from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator

import matplotlib.pyplot as plt

from scipy.misc import imread

# In[6]:

#读取一个txt文件,把上面的文本文档内容复制到一个叫word.txt的文档中,自定义路径

text = open('D:\\Python\\notebook\\word.txt','r').read()

print(text)

# In[3]:

#使用背景图片制作词云图片

'''

mask : nd-array or None (default=None) //如果参数为空,则使用二维遮罩绘制词云。如果 mask 非空,设置的宽高值将被忽略,遮罩形状被 mask 取代。

       除全白(#FFFFFF)的部分将不绘制,其余部分会都绘制词云。如:bg_pic = imread('读取一张图片.png'),背景图片画布一定要设置为白色(#FFFFFF),

       然后显示的形状为不是白色的其他颜色。可以用ps工具将自己要显示的形状复制到一个纯白色的画布上再保存,就ok了。

background_color : color value (default=”black”) //背景颜色,如background_color='black',背景颜色为黑色。

scale : float (default=1) //按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍。

generate(text)  //根据文本生成词云

'''

#读入背景图片

bg_pic = imread('D:\\Python\\notebook\\love.jpg')

#生成词云

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

# 从背景图片生成颜色值

image_colors = ImageColorGenerator(bg_pic)

#显示词云图片

plt.imshow(wordcloud)

plt.axis('off')

plt.show()

# In[7]:

#不使用背景图片制作词云图

#生成词云

wordcloud = WordCloud(background_color='black',scale=1.5).generate(text)

#显示词云图片

plt.imshow(wordcloud)

plt.axis('off')

plt.show()

# In[5]:

#保存图片

#wordcloud.to_file('D:\\Python\\notebook\\test.jpg')

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,807评论 6 518
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 95,284评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 169,589评论 0 363
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 60,188评论 1 300
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 69,185评论 6 398
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,785评论 1 314
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,220评论 3 423
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 40,167评论 0 277
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,698评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,767评论 3 343
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,912评论 1 353
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,572评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,254评论 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,746评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,859评论 1 274
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,359评论 3 379
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,922评论 2 361

推荐阅读更多精彩内容