Python詞雲庫wordcloud中文顯示問題詳解

LarryHai6發表於2019-01-23

Python詞雲庫wordcloud中文顯示問題詳解


背景:

wordcloud是基於Python開發的詞雲生成庫,功能強大使用簡單。

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

wordcloud預設是不支援顯示中文的,中文會被顯示成方框。

這裡寫圖片描述
安裝:

方法一:

pip3 install wordcloud

方法二:

下載.whl檔案http://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud
改字尾為.zip檔案,解壓。然後放到python安裝的對應資料夾
(https://github.com/amueller/word_cloud/archive/master.zip)

python setup.py install

解決不支援中文:

經過測試發現不支援顯示中文的原因是因為wordcloud的預設字型不支援中文,那就好辦了,我們設定一種支援中文的字型即可

方法一:
百度下載字型simhei.ttf放到對應C:\Windows\Fonts裡

方法二:
wordlcloud.WordCloud類初始化函式有個設定字型的引數font_path,把支援中文的字型的路徑傳給font_path。

github有個Adobe開源的支援中文的字型庫:https://github.com/adobe-fonts

我們以英文夾雜著中文的Python之禪字串來測試一下,下面的程式碼是在Windows下測試,使用了仿宋字型。(兩種方法處理文字:1.從檔案讀取 2.直接賦值給字串)

# -*- coding: utf-8 -*-

from wordcloud import WordCloud
import matplotlib.pyplot as plt

text= open("test.txt").read()
"""
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 impleme 武漢 ntation 想你 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')  # 把詞雲儲存下來

    生成的詞雲圖:

相關文章