分享

解决Python词云库wordcloud不显示中文的问题

 悦思无邪 2017-06-06

背景:

wordcloud是基于Python开发的词云生成库,功能强大使用简单。

github地址:https://github.com/amueller/word_cloud

wordcloud默认是不支持显示中文的,中文会被显示成方框。



安装:

安装命令:

pip install wordcloud

解决:

经过测试发现不支持显示中文的原因是因为wordcloud的默认字体不支持中文,那就好办了,我们设置一种支持中文的字体即可, wordlcloud.WordCloud类初始化函数有个设置字体的参数font_path,把支持中文的字体的路径传给font_path
我们以英文夹杂着中文的Python之禅字符串来测试一下,下面的代码是在Windows下测试,使用了仿宋字体。

# -*- coding: utf-8 -*- from wordcloud import WordCloud import matplotlib.pyplot as plt text = '''文案 文案 The 抱抱 Zen of LOVE 抱抱 Python, 快乐 by Tim Peters 公众号 公众号 Python 最好的 语言 语言 一辈子 is better LOVE than 一辈子. 喵小姐 is 爱你 than implicit.爱你 喵小姐 蟹先生 is 爱你 than complex. 一辈子 is 蟹先生 than complicated. 二中 is 喵小姐 我想你了 than nested. 二中 蟹先生 清湖 is 胜于 than 清湖. 思旺 counts. 想你 Special 喵小姐 我想你了 aren't special enough 思旺 break 思旺 rules. 别生气 practicality beats 厨艺好. Errors should 我想你了 never pass 小龙虾 silently. 运营 别生气 explicitly 好不好. LOVE In the face of ambiguity, 程序员 the 厨艺好 to guess.龙华 龙华 There 快乐 should be one-- 我想你了 and preferably 红烧肉 only one 小龙虾--obvious way to do it.运营 Although 共享单车 way may not 我想你了 be obvious at first unless you're Dutch. 新媒体 地铁 Now is better 红烧肉 than never. 程序员 Although 共享单车 is often 高铁 than 东莞 now. 高铁 地铁 If the implementation 想你 is hard to explain, it's a bad idea. 想你了 If 成都 implementation is 想你 easy to explain, it may be a good idea. Namespaces are 端午one 端午 honking great idea -- 成都 do more of those! 想你了 深圳 晚安 深圳 新媒体 ''' # the font from github: https://github.com/adobe-fonts font = r'C:\Windows\Fonts\simfang.ttf' wc = WordCloud(collocations=False, font_path=font, width=1400, height=1400, margin=2).generate(text.lower()) plt.imshow(wc) plt.axis('off') plt.show() wc.to_file('show_Chinese.png') # 把词云保存下来

生成的词云图:



github有个Adobe开源的支持中文的字体库:https://github.com/adobe-fonts


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多