gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:39:43 24 4
gpt4 key购买 nike

我想创建一个词云。当我的字符串是英文时,一切正常:

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

有什么想法吗?

最佳答案

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

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

from wordcloud import WordCloud
from matplotlib import pyplot as plt

text="""תחילתו של חורף מאכזב למדיי, מומחי המים בישראל מאמינים כי לראשונה השנה מפלס הכנרת יעלה בצורה משמעותית מגשמי הסערה שתחל היום"""
wordcloud = WordCloud(<b>font_path='/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'</b>).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 = <b>get_display(text)</b>

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

关于python - 在 python 中为外语(希伯来语)创建 wordcloud,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54063438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com