masked.py 871 Bytes
Newer Older
Andreas Mueller's avatar
Andreas Mueller committed
1
#!/usr/bin/env python2
Andreas Mueller's avatar
Andreas Mueller committed
2
3
4
5
6
"""
Masked wordcloud
================
Using a mask you can generate wordclouds in arbitrary shapes.
"""
Andreas Mueller's avatar
Andreas Mueller committed
7
8

from os import path
9
10
import Image
import numpy as np
Andreas Mueller's avatar
Andreas Mueller committed
11
12
13
14
15
16
17
18
19
20
21
22
import matplotlib.pyplot as plt

from wordcloud import WordCloud, STOPWORDS

d = path.dirname(__file__)

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

# read the mask image
# taken from
# http://www.stencilry.org/stencils/movies/alice%20in%20wonderland/255fk.jpg
23
alice_mask = np.array(Image.open(path.join(d, "alice_mask.png")))
Andreas Mueller's avatar
Andreas Mueller committed
24
25
26

wc = WordCloud(background_color="white", max_words=2000, mask=alice_mask,
               stopwords=STOPWORDS.add("said"))
27
# generate word cloud
Andreas Mueller's avatar
Andreas Mueller committed
28
wc.generate(text)
29
30
31
32
33

# store to file
wc.to_file(path.join(d, "alice.png"))

# show
Andreas Mueller's avatar
Andreas Mueller committed
34
plt.imshow(wc)
Andreas Mueller's avatar
Andreas Mueller committed
35
36
37
38
plt.axis("off")
plt.figure()
plt.imshow(alice_mask, cmap=plt.cm.gray)
plt.axis("off")
Andreas Mueller's avatar
Andreas Mueller committed
39
plt.show()