In [2]:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from os import path
from wordcloud import WordCloud

d = path.dirname("__file__")

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

# Generate a word cloud image
wordcloud = WordCloud().generate(text)

# lower max_font_size
wordcloud = WordCloud(max_font_size=40).generate(text)
fig = plt.figure()
fig.suptitle('Lord Of The Rings Simple Word Cloud', fontsize=14, fontweight='bold', color = "orange")
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
In [3]:
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

d = path.dirname("__file__")

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

# read the mask / color image taken from
# https://thebests.kotaku.com/the-best-lord-of-the-rings-video-games-1820380737
gandolf_coloring = np.array(Image.open(path.join(d, "gandolf.jpg")))
stopwords = set(STOPWORDS)
stopwords.add("said")

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

# create coloring from image
image_colors = ImageColorGenerator(gandolf_coloring)

# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
fig = plt.figure()
fig.suptitle('Lord Of The Rings Word Cloud', fontsize=14, fontweight='bold', color = "orange")

plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(gandolf_coloring, cmap=plt.cm.gray, interpolation="bilinear")
plt.axis("off")
plt.show()