只需要提供文本数据以及轮廓照片即可
stopword为wordcloud自带的关键参数,可去掉不想要的文字
import jieba
from matplotlib import pyplot as plt
import wordcloud
from PIL import Image
import numpy as np
#r''单引号里面不需要转义
path = r'D:\Pycharm\.idea\frist_YF_project\Expy'
font = r'C:\Windows\Fonts\simsun.ttc'#电脑自带的字体
def tcg(texts):
cut = jieba.cut(texts) #分词
string = ' '.join(cut)
return string
text = (open(r'.\cloudtxtbad.txt','r',encoding='utf-8')).read()
string=tcg(text)
img = Image.open(r'.\cloud.png') #打开图片
img_array = np.array(img) #将图片装换为数组
stopword=['there','with','have','from',r'didn t','but','I','the','and','for','to','was','a','we','very',
'of','it','in','is','my','they','were','not','at','had','no','that'] #设置停止词,也就是你不想显示的词
wc = wordcloud.WordCloud(
background_color='white',
width=1000,
height=800,
mask=img_array, #设置背景图片
font_path=font,
collocations=True,
stopwords=stopword
)
wc.generate_from_text(string)#绘制图片
plt.imshow(wc)
plt.axis('off')
plt.show() #显示图片
wc.to_file(r'.\beautifulcloud.png') #保存图片