48 lines
1.1 KiB
Python
Executable File
48 lines
1.1 KiB
Python
Executable File
#!/usr/bin/env python
|
|
"""
|
|
Masked wordcloud
|
|
================
|
|
|
|
Using a mask you can generate wordclouds in arbitrary shapes.
|
|
"""
|
|
|
|
import os
|
|
from os import path
|
|
|
|
import matplotlib.pyplot as plt
|
|
import numpy as np
|
|
from PIL import Image
|
|
from wordcloud import STOPWORDS, ImageColorGenerator, WordCloud
|
|
|
|
# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
|
|
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
|
|
|
|
# Read the whole text.
|
|
text = open(path.join(d, "work.txt")).read()
|
|
|
|
# read the mask image
|
|
# image from: https://all-free-download.com/free-vector/download/farm-cow-icon-colored-cartoon-sketch_6843157.html
|
|
image_mask = np.array(Image.open(path.join(d, "cow-color.png")))
|
|
image_colors = ImageColorGenerator(image_mask)
|
|
|
|
stopwords = set(STOPWORDS)
|
|
stopwords.add("said")
|
|
|
|
wc = WordCloud(
|
|
background_color="white",
|
|
max_words=750,
|
|
mask=image_mask,
|
|
stopwords=stopwords,
|
|
contour_width=3,
|
|
color_func=image_colors,
|
|
height=1080,
|
|
width=1920,
|
|
min_word_length=3,
|
|
)
|
|
|
|
# generate word cloud
|
|
wc.generate(text)
|
|
|
|
# store to file
|
|
wc.to_file(path.join(d, "../cow-wordcloud.png"))
|