根据给出alice.txt文档,制作词云图片(文件名为
a1.png),格式要求:背景色为白色,去除重复的词,图片宽度为300,高度为200
将分词后的生成器对象转换为列表再用set去重。完整代码如下,
import jieba
import wordcloud
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
#读取文本
with open("alice.txt", "r", encoding="utf-8") as f:
s = f.read()
#分词
words = list(jieba.cut(s))
#去重
words=set(words)
txt = " ".join(words)
#背景图片
mask=np.array(Image.open("F:/2021/qa/ot1/star.jpg"))
#生成词云图
w = wordcloud.WordCloud(mask=mask,max_words=100,width=300, height=200, background_color="white", font_path="msyh.ttc").generate(txt)
w.to_file("a1.png")
#词云图展示
plt.axis('off')
plt.imshow(w,interpolation='bilinear')
plt.show()
如有帮助,请点采纳该回答按钮
import jieba
import wordcloud
t=''
with open("alice.txt", "r", encoding="utf-8") as f:
t = f.read()
# 去重
t=''.join(list(set(list(t))))
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(width=300, height=200, background_color="white", font_path="msyh.ttc")
w.generate(txt)
w.to_file("a1.png")