在python中为外语(希伯来语)创建wordcloud

时间:2019-01-06 16:13:47

标签: python algorithm text data-visualization word-cloud

我想创建一个wordcloud。 当我的字符串为英语时,一切正常:

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

但是当我在希伯来语中执行相同操作时,它不会检测字体,并且我只会得到空矩形:

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

enter image description here

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

这与wordcloud本身并没有多大关系,而与呈现关系更大:您使用(默认是)一种字体,该字体根本不包含任何希伯来字符的“定义”。因此,它只是简单地呈现矩形。

但是,我们可以使用支持希伯来语字符的字体,例如 FreeSansBold 。我们可以通过WordCloud构造函数传递字体的路径:

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

然后将生成以下词云:

wordcloud generated with another font

我对希伯来语不是很熟悉,但是我的印象是单词是从左到右书写的,而不是从右到左书写的。无论如何,如果这是一个问题,我们可以使用python-bidi首先处理语言的方向,例如:

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

对于给定的文本,我们将获得以下图像:

wordcloud with Hebrew right-to-left