masked.py 918 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
from PIL import Image
10
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
27
stopwords = set(STOPWORDS)
stopwords.add("said")

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

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

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