Python WordCloud Tutorial: Guide & Examples
To use the wordcloud library in Python, you first need to install it. You can install it using the pip command.
pip install wordcloud
After installation is complete, you can follow these steps to use the wordcloud library to generate a word cloud:
- Import the wordcloud and matplotlib libraries.
from wordcloud import WordCloud
import matplotlib.pyplot as plt
- Prepare text data, it can be a paragraph of text or a text file.
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget mauris vitae nisi scelerisque gravida. ..."
Or read data from a text file.
with open('sample.txt', 'r') as file:
text = file.read()
- Create a WordCloud object and generate a word cloud image.
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
This will display a word cloud image where words with higher frequency appear larger, and words with lower frequency appear smaller. You can customize the style of the word cloud image by adjusting parameters of the WordCloud object such as width, height, background color, etc.