import wordcloud
font = 'C:\Windows\Fonts\ITCEDSCR.TTF'
file = open('D:\python1\pythonProject\copypoetry.txt',encoding='UTF-8')
string = str(file.read())
file.close()
w = wordcloud.WordCloud(font_path=font,max_words=500,max_font_size=40,backgroud_color='white')
w.generate(string)
w.to_file('ss.png')
下面的是运行结果
D:\python1\pythonProject\venv\Scripts\python.exe D:/python1/pythonProject/poetry.py
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\H1831\AppData\Local\Temp\jieba.cache
Loading model cost 1.261 seconds.
Prefix dict has been built successfully.
Process finished with exit code 0
你试试我这个
import hanlp
import imageio
import wordcloud
def tokenizer_zh(text):
tokenizer = hanlp.load('PKU_NAME_MERGED_SIX_MONTHS_CONVSEG')
result = tokenizer(text)
return result
'''generate word cloude'''
def gen_wordcloud_zh(text, mask_path, out_path):
word_list = tokenizer_zh(text)
word_list = [word for word in word_list if len(word.strip())>1]#清洗一个字的词
word_clean=" ".join(word_list)
mask=imageio.imread(mask_path)
wc = wordcloud.WordCloud(font_path = "simkai.ttf",#指定字体类型
background_color = "white",#指定背景颜色
max_words = 200, # 词云显示的最大词数
max_font_size = 255,#指定最大字号
mask = mask) #指定模板
wc.generate(word_clean)##生成词云
wc.to_file(out_path)
# plt.imshow(wc)
# plt.axis("off")
# plt.show()
应该是没有设置mask,我以前遇到过