在python下使用wordcloud生成词云,由于程序默认字体不支持中文,所以不能正确显示。
一种是改进wordcloud.py.找到如下图的第28行所示内容
FONT_PATH = os.environ.get('FONT_PATH', os.path.join(FILE, 'DroidSansMono.ttf'))
将DroidSansMono.ttf改为你想要的字体,但不推荐这种方法。可以在构造wordcloud时设定字体。
wordcloud = WordCloud(background_color="white", width=800, height=600, margin=2, font_path='MSYH.TTC', max_words=200 ).generate(wl_space_split)
附,中文词云使用
#导入所需库 import jieba from wordcloud import WordCloud f = open('wordCloud.txt','rt', encoding='utf-8').read() wordlist_after_jieba = jieba.cut(f, cut_all=True) wl_space_split = " ".join(wordlist_after_jieba) wordcloud = WordCloud(background_color="white", width=800, height=600, margin=2, font_path='MSYH.TTC', max_words=200 ).generate(wl_space_split) import matplotlib.pyplot as plt plt.imshow(wordcloud) plt.axis("off") plt.show() wordcloud.to_file('test.png') # 保存图片,但是在第三模块的例子中 图片大小将会按照 mask 保存