import sys
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
def generate_wordcloud(filename, output_image='wordcloud.png', width=1200, height=800):
"""
Generate a word cloud from a text file and save/display it.
Args:
- filename (str): Path to the input text file.
- output_image (str): Path to save the word cloud image (default: 'wordcloud.png').
- width (int): Width of the word cloud image.
- height (int): Height of the word cloud image.
"""
try:
# Read the text file
with open(filename, 'r', encoding='utf-8') as file:
text = file.read()
if not text.strip():
print("Error: The file is empty.")
return
# Create WordCloud object with custom stopwords
stopwords = set(STOPWORDS)
stopwords.update(['the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by']) # Add more if needed
wordcloud = WordCloud(
width=width,
height=height,
background_color='white',
stopwords=stopwords,
collocations=False, # Avoid repeating common bigrams
random_state=42 # For reproducible results
).generate(text)
# Plot the word cloud
plt.figure(figsize=(12, 8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.tight_layout(pad=0)
plt.show()
# Save the word cloud to file
wordcloud.to_file(output_image)
print(f"Word cloud generated and saved as '{output_image}'")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
except Exception as e:
print(f"Error: {str(e)}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python wordcloud.py <input_filename.txt>")
print("Example: python wordcloud.py mytext.txt")
sys.exit(1)
input_file = sys.argv[1]
generate_wordcloud(input_file)
How to Use:
-
Install required packages (if not already installed):
pip install wordcloud matplotlib
-
Prepare your text file: Save your text in a file, e.g., input.txt.
-
Run the script:
python wordcloud.py input.txt
- A window will pop up showing the word cloud.
- It will also save the image as
wordcloud.png in the current directory.
Features:
- Handles UTF-8 encoding for international text.
- Customizable stopwords to filter common words.
- Configurable size via function parameters.
- Error handling for missing/empty files.
- Collocations disabled to avoid over-representing phrases like "New York".
- Reproducible with fixed random seed.
This script is efficient for large files and produces publication-ready word clouds!