2 min read

Word Cloud Generator

This utility generates a word cloud from a text source. A word cloud is a visual representation of text data where the size of each word indicates its frequency or importance.

Modules Used:

  • wordcloud: To generate the word cloud image.
  • matplotlib: To display the generated image.
  • argparse: To handle command-line arguments.

Installation

pip install wordcloud matplotlib

The Code

Save this as wordcloud_gen.py.

from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import argparse
import os
import sys

def generate_wordcloud(text, output_file=None, background_color='black'):
    try:
        print("Generating word cloud...")

        # Create WordCloud object
        # stopwords: set of words to ignore (e.g., "the", "is", "and")
        wc = WordCloud(
            width=800, 
            height=400, 
            background_color=background_color,
            stopwords=STOPWORDS,
            min_font_size=10
        ).generate(text)

        # Display or Save
        if output_file:
            wc.to_file(output_file)
            print(f"Success! Saved to '{output_file}'")
        else:
            print("Displaying word cloud...")
            plt.figure(figsize=(8, 8), facecolor=None)
            plt.imshow(wc)
            plt.axis("off")
            plt.tight_layout(pad=0)
            plt.show()

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Word Cloud Generator")
    parser.add_argument("input", help="Text string OR path to a text file")
    parser.add_argument("-o", "--output", help="Output image filename (e.g., cloud.png). If omitted, displays on screen.")
    parser.add_argument("--bg", default="black", help="Background color (default: black)")

    args = parser.parse_args()

    # Check if input is a file path
    text_data = args.input
    if os.path.isfile(args.input):
        try:
            with open(args.input, 'r', encoding='utf-8') as f:
                text_data = f.read()
            print(f"Read content from file: {args.input}")
        except Exception as e:
            print(f"Error reading file: {e}")
            sys.exit(1)

    generate_wordcloud(text_data, args.output, args.bg)

Usage

# Generate from a string and display
python wordcloud_gen.py "Python is amazing and Python is fun"

# Generate from a file and save to PNG with white background
python wordcloud_gen.py speech.txt --output speech_cloud.png --bg white

programming/python/python