Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create wordcloud in python for foreign language (Hebrew)

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()

enter image description here

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()

enter image description here

Any ideas?

like image 594
Binyamin Even Avatar asked Jan 06 '19 16:01

Binyamin Even


1 Answers

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:

wordcloud generated with another font

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:

wordcloud with Hebrew right-to-left

like image 195
Willem Van Onsem Avatar answered Oct 19 '22 01:10

Willem Van Onsem