-->

create wordcloud in python for foreign language (H

2020-07-11 08:47发布

问题:

I want to create a wordcloud. When my string is in English, everything works fine:

from wordcloud import WordCloud
from matplotlib import pyplot as plt
text="""Softrock 40 - close to the 6 MHz that the P6D requires (6.062 according) - https://groups.yahoo.com/neo/groups/softrock40/conversations/messages
I want the USB model that has a controllable (not fixed) central frequency."""
wordcloud = WordCloud().generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

But when I'm doing the same in Hebrew, it doesn't detect the font, and I get only empty rectangles:

text="""תחילתו של חורף מאכזב למדיי, מומחי המים בישראל מאמינים כי לראשונה השנה מפלס הכנרת יעלה בצורה משמעותית מגשמי הסערה שתחל היום"""
wordcloud = WordCloud().generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

Any ideas?

回答1:

This has not that much to do with the wordcloud itself, but more with the rendering: you use (well the default is) a font that simply does not contains any "definitions" for Hebrew characters. It thus simply renders rectangles instead.

We can however use a font that supports Hebrew characters, for example FreeSansBold. We can pass a path to the font through the WordCloud constructor:

from wordcloud import WordCloud
from matplotlib import pyplot as plt

text="""תחילתו של חורף מאכזב למדיי, מומחי המים בישראל מאמינים כי לראשונה השנה מפלס הכנרת יעלה בצורה משמעותית מגשמי הסערה שתחל היום"""
wordcloud = WordCloud(font_path='/usr/share/fonts/truetype/freefont/FreeSansBold.ttf').generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

then this generates the following word cloud:

I'm not very familiar with Hebrew, but I have the impression that the words are written left-to-right, instead of right-to-left. Anyway, if that is an issue, we can use python-bidi to first process the direction of a language, like:

from wordcloud import WordCloud
from matplotlib import pyplot as plt
from bidi.algorithm import get_display

text="""תחילתו של חורף מאכזב למדיי, מומחי המים בישראל מאמינים כי לראשונה השנה מפלס הכנרת יעלה בצורה משמעותית מגשמי הסערה שתחל היום"""

bidi_text = get_display(text)

wordcloud = WordCloud(font_path='/usr/share/fonts/truetype/freefont/FreeSansBold.ttf').generate(bidi_text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

For the given text, we then obtain the following image: