wordcloud默認是不支持顯示中文的,中文會被顯示成方框。
wordlcloud.WordCloud類初始化函數有個設置字體的參數font_path,把支持中文的字體的路徑傳給font_path。
如下:
from wordcloud import WordCloud
f = open('testfile.txt', 'r')
txt=f.read()
wordcloud = WordCloud(font_path="ygyxsziti2.0.ttf",background_color="black", width=800, height=860, margin=2).generate(txt)
wordcloud.to_file('test1.png')//保存圖片
這樣,不顯示中文的問題就解決了。