Word Cloud Generator in Python
Word Cloud Generator: Build a program that generates a word cloud from a given text.
Input values:
User provides text or a document from which the word cloud will be generated.
Output value:
Visual representation of the word cloud generated from the provided text or document.
Example:
Input values: Text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." Output value: Visual representation of the word cloud generated from the provided text, where frequently occurring words like "Lorem," "ipsum," "dolor," "sit," "amet," etc., are displayed in larger font sizes than less frequent words. Input values: Text: "In hac habitasse platea dictumst. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta." Output value: Visual representation of the word cloud generated from the provided text, where frequently occurring words like "habitas," "platea," "dictumst," "Vivamus," "suscipit," etc., are displayed in larger font sizes than less frequent words.
Solution: Using the wordcloud Library
Code:
# Import necessary libraries
from wordcloud import WordCloud # Import WordCloud for generating word clouds
import matplotlib.pyplot as plt # Import matplotlib for displaying the word cloud
# Define a function to generate and display a word cloud
def generate_word_cloud(text):
"""
Generates and displays a word cloud from the given text.
Args:
text (str): The input text for generating the word cloud.
"""
# Create a WordCloud object
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
# Display the generated word cloud using matplotlib
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off') # Hide axis
plt.show()
# Example text input
text = "Build a program that generates a word cloud from a given text"
# Call the function with the example text
generate_word_cloud(text)
Output:
Explanation:
- Library Imports: Imports WordCloud for generating the word cloud and matplotlib.pyplot for displaying it.
- Function Definition: Defines generate_word_cloud to handle the word cloud creation and visualization.
- WordCloud Object: Uses WordCloud to generate a word cloud, specifying dimensions and background color.
- Display with Matplotlib: Configures and displays the word cloud with matplotlib.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/projects/python/python-project-word-cloud-generator.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics