根据文本comment.text和图片a4.png制作词云,注意要将文本、图片与.py代码文件放于同一文件夹下运行
文本:
图片:
import jieba,wordcloud
import imageio
def getText():
txt = open("comment.text","r",encoding="utf-8").read()
return txt
#获取文本信息并切割
txt = getText()
txt = jieba.lcut(txt)
# print(txt)
#创建一个列表,存入长度大于1的词语
words = []
for word in txt:
if len(word) == 1:
continue
else:
words.append(word)
txt = words
# print(txt)
pic = imageio.imread("a4.png")
txt = " ".join(txt)
w = wordcloud.WordCloud(width = 1000, height = 700,\
background_color = "white",\
font_path = "msyh.ttc",\
mask = pic,\
contour_color="red",\
contour_width=5,\
mode="RGB")
w.generate(txt)
w.to_file("experiment.png")
在运行代码后会发现文件夹下多了一个experiment.png文件
效果: