Python WordCloud入门

最近一段时间在爬取文本信息,后面就要开始处理了。刚刚get了一个新的 词频统计和展示模块WordCloud。

1.WordCloud安装


首先,需要从github上下载WordCloud安装包https://github.com/amueller/word_cloud
其次,解压、安装WordCloud,因为我是打算将WordCloud导入Anaconda里的,所以先打开Anaconda Propmt,将路径切换到WordCloud目录下,执行python setup.py install,安装过程如下图所示:
这里写图片描述

这里写图片描述

2.WordCloud 测试


安装好之后,用官方给出的alice案例来做一个测试,在测试过程中,需要读取到两个文件,alice.txt和alice_color.png。其中,alice.txt为输入文本,alice_color.png作为输出词云的背景图片。具体代码如下所示:

# -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 09:49:45 2017

@author: zch
"""

from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

d = path.dirname(__file__)

# Read the whole text.
text = open(path.join(d, 'alice.txt')).read()

# read the mask / color image taken from
# http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010
alice_coloring = np.array(Image.open(path.join(d, "alice_color.png")))
stopwords = set(STOPWORDS)
stopwords.add("said")

wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,
               stopwords=stopwords, max_font_size=75, random_state=42)
# generate word cloud
wc.generate(text)

# create coloring from image
image_colors = ImageColorGenerator(alice_coloring)

# show
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.figure()
# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")
plt.axis("off")
plt.show()

背景图片如下所示:
这里写图片描述
在实际操作过程中,为了对比下文本长度对词云生成效果的影响,alice.txt分别读取了两个不同的文本,第一个文本里存放一段有关wordcloud的英文介绍,大概有数百字符,第二个文本里存放Alice’s Adventures in Wonderland (爱丽丝梦游仙境)整本书的内容,两次测试的效果图如下所示:
这里写图片描述
这里写图片描述
观察对比上面两张效果图,可以明显看出随着文本内容数量级的增加,生成的词云轮廓表现能力更强。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值