How to Create a Word Cloud in Python
The wordcloud library turns a block of text into an image where word size reflects frequency. You pass it your text, set the width, height and background color, then save the result as a PNG file with one method call. Common stop words are filtered out by default.
Install the libraries
You need two packages, because wordcloud depends on matplotlib. Run both commands in your command prompt:
pip install matplotlibpip install wordcloud
The sample text, a speech by Jeff Bezos saved as jeff_bezos_speech.txt, and the script are in the GitHub repository. Any plain text file works.
Build the script
Create a Python file in the folder that holds the text file. I named mine wordcloud_example.py. Start with the imports:
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
Read the text file into a variable. Passing encoding='utf-8' avoids errors with special characters:
text = open('jeff_bezos_speech.txt', 'r', encoding='utf-8').read()
Stop words are common words such as “the” and “and” that would otherwise dominate the cloud. The package ships a default list, which you can copy and extend:
stopwords = set(STOPWORDS)
Create the WordCloud object with the background color, the stop words and the image size, then generate the cloud from the text:
wc = WordCloud(background_color='white', stopwords=stopwords, height=600, width=400)
wc.generate(text)
Save the image to a file:
wc.to_file('wordcloud_output.png')
Full script
This is the complete script from the GitHub repo. It builds the file path with pathlib, so it finds the text file as long as you run it from the project folder. Running it creates wordcloud_output.png in the same folder.
from pathlib import Path
import matplotlib.pyplot as plt
from wordcloud import STOPWORDS, WordCloud
TXT_FILE = Path.cwd() / "jeff_bezos_speech.txt"
# Read text
text = open(TXT_FILE, mode="r", encoding="utf-8").read()
stopwords = STOPWORDS
wc = WordCloud(background_color="white", stopwords=stopwords, height=600, width=400)
wc.generate(text)
# store to file
wc.to_file("wordcloud_output.png")
The script imports matplotlib.pyplot but never uses it, because it only saves a file. You need it only if you want to show the cloud in a window.
Customize the result
These parameters of WordCloud change the look:
- max_font_size: the largest word size.
- min_font_size: the smallest word size.
- color_func: a function that picks the color of each word.
- mask: an image that gives the cloud its shape.
To hide extra words, add them to the stop word set, for example stopwords.update(["will", "one"]). The official documentation lists every option. If you want other kinds of charts from your data, try hand-drawn charts with cutecharts or a calendar heatmap with plotly.
