How to draw a word cloud?ΒΆ
The wordcloud library draws word clouds from a string of words. It allows to create clouds in arbitrary shapes, using a NumPy array as a mask.
Install the library with:
pip install wordcloud
Then create the cloud image:
import numpy as np
from matplotlib import pyplot as plt
import wordcloud
import this
# extract the Zen of Python to a string
text: str = ''.join([this.d.get(c, ' ') for c in this.s]).lower()
# leave a blank square in the cloud
mask = np.zeros((500, 500, 3), np.uint8)
mask[150:350,150:350,:] = 255
cloud = wordcloud.WordCloud(background_color="white",
max_words=50,
mask=mask,
collocations=False,
contour_color='steelblue').generate(text)
plt.figure(num = None, figsize = (8, 8))
plt.imshow(cloud, interpolation='bilinear')
plt.xticks([], None)
plt.yticks([], None)
plt.savefig('cloud.png')
plt.show()
See also