从《荷塘月色》提词绘制词云图
![](https://i-blog.csdnimg.cn/blog_migrate/9c046383fca9d2b5782183ff313db668.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/047a6b2fc728f27854ecf9489c6f3eb9.png)
code
import jieba
import numpy as np
from PIL import Image
from wordcloud import WordCloud
def gen_wordcloud(text_file, mask_img):
"""
Parameters
----------
text_file :一个文本文件名,函数对此文件生成词云
mask_img : 一个.jpg文件名,词云mask的图像文件
Returns
-------
None.
函数读取text_file,以mask_img为背景生成词云
"""
mask = np.array(Image.open(mask_img))
# 从此处继续书写函数gen_wordcloud的代码
with open(text_file, encoding='utf-8') as f:
text = f.read()
raw = list(jieba.cut(text))
word = {}
for i in raw:
if len(i) > 1:
if i not in word:
word[i] = 1
else:
word[i] += 1
wc = WordCloud(font_path='msyh.ttc', background_color='white', max_words=120, mask=mask, width=1000, height=800)
wc.generate_from_frequencies(word)
wc.to_file('词云.png')
if __name__ == '__main__':
gen_wordcloud('./荷塘月色.txt', './cloud.jpg')
![](https://i-blog.csdnimg.cn/blog_migrate/2f04fa4524120442bd6b0370bd5acb23.png)