您的位置:首页 > 编程语言 > Python开发

Python WordCloud入门

2017-03-31 10:51 489 查看
最近一段时间在爬取文本信息,后面就要开始处理了。刚刚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 (爱丽丝梦游仙境)整本书的内容,两次测试的效果图如下所示:





观察对比上面两张效果图,可以明显看出随着文本内容数量级的增加,生成的词云轮廓表现能力更强。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python WordCloud