a_new_hope.py 1.4 KB
Newer Older
1
#!/usr/bin/env python
Andreas Mueller's avatar
Andreas Mueller committed
2 3 4 5 6 7
"""
Using custom colors
====================
Using the recolor method and custom coloring functions.
"""

8
import numpy as np
9
from PIL import Image
Andreas Mueller's avatar
Andreas Mueller committed
10 11 12 13 14 15 16
from os import path
import matplotlib.pyplot as plt
import random

from wordcloud import WordCloud, STOPWORDS


Andreas Mueller's avatar
Andreas Mueller committed
17
def grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs):
Andreas Mueller's avatar
Andreas Mueller committed
18 19 20 21 22 23 24
    return "hsl(0, 0%%, %d%%)" % random.randint(60, 100)

d = path.dirname(__file__)

# read the mask image
# taken from
# http://www.stencilry.org/stencils/movies/star%20wars/storm-trooper.gif
25
mask = np.array(Image.open(path.join(d, "stormtrooper_mask.png")))
Andreas Mueller's avatar
Andreas Mueller committed
26 27 28 29 30 31 32 33 34 35 36

# movie script of "a new hope"
# http://www.imsdb.com/scripts/Star-Wars-A-New-Hope.html
# May the lawyers deem this fair use.
text = open("a_new_hope.txt").read()

# preprocessing the text a little bit
text = text.replace("HAN", "Han")
text = text.replace("LUKE'S", "Luke")

# adding movie script specific stopwords
37
stopwords = set(STOPWORDS)
Andreas Mueller's avatar
Andreas Mueller committed
38 39 40 41 42 43 44 45 46
stopwords.add("int")
stopwords.add("ext")

wc = WordCloud(max_words=1000, mask=mask, stopwords=stopwords, margin=10,
               random_state=1).generate(text)
# store default colored image
default_colors = wc.to_array()
plt.title("Custom colors")
plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3))
Andreas Mueller's avatar
Andreas Mueller committed
47
wc.to_file("a_new_hope.png")
Andreas Mueller's avatar
Andreas Mueller committed
48 49 50 51 52 53
plt.axis("off")
plt.figure()
plt.title("Default colors")
plt.imshow(default_colors)
plt.axis("off")
plt.show()