Python, pip Installation configuration ;
Install dependent packages ( Use -i url
Specify the mirror source to use , Faster downloads )
pip install wordcloud scipy jieba
If the download speed is too slow , Add parameters -i https://pypi.tuna.tsinghua.edu.cn/simple
Use domestic image to download .
.ttf
At the end of the , It's a font file , What I chose was simfang.ttf
.mask
Set the background .Pay attention to the relative path and the absolute path .
If you use the relative path to load the file , Execute this py Script time , Should first cd
Go to the directory where the script is located , then :
python test-wordcloud.py
test-wordcloud.py
from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS
import matplotlib.pyplot as plt
import scipy.misc as imread
import jieba
# The path of the text file to be analyzed
text_file_paths = " Yuhua - Alive .txt"
# Custom word cloud background image path ( Not set up )
mask_file_path = "bg.jpg"
# Chinese font path
font_path = "C:\Windows\WinSxS\amd64_microsoft-windows-font-truetype-simfang_31bf3856ad364e35_10.0.18362.1_none_5a7f93f39ed619f0\simfang.ttf"
# The result path to be generated
result_file_path = "result.jpg"
mask_img = plt.imread(mask_file_path)
with open(text_file_paths, "r", encoding="UTF-8") as f:
text = f.read()
wordlist_after_jieba = jieba.cut(text, cut_all=True)
wl_space_split = " ".join(wordlist_after_jieba)
wc = WordCloud(
background_color="white",
font_path=font_path,
# mask=mask_img, # Whether or not the background image specified by yourself
prefer_horizontal=0.9, # The proportion of word level display
width=500,
height=300,
scale=10,
max_words=500,
relative_scaling=0.5,
stopwords=STOPWORDS,
max_font_size=70,
collocations=False,
min_word_length=2,
)
wc.generate(wl_space_split)
# Custom image background shape 、 Color
# image_colors = ImageColorGenerator(mask_img)
# wc.recolor(color_func=image_colors)
# Write to the picture file
wc.to_file(result_file_path)
# display picture
plt.imshow(wc)
plt.axis("off")
plt.show()
Do not configure Chinese font file , There's a little square code :
After configuring the Chinese font :
After you specify your own background image ( The width and height of the picture will cover our word cloud width height
To configure ):
Color scheme of your own picture :