代码之家  ›  专栏  ›  技术社区  ›  Binyamin Even

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

  •  2
  • Binyamin Even  · 技术社区  · 6 年前

    我想创建一个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 回复  |  直到 6 年前
        1
  •  2
  •   willeM_ Van Onsem    6 年前

    这与wordcloud本身没有太多的关系,而是与渲染有更多的关系:您使用的字体(默认为)只是不包含希伯来语字符的任何“定义”。因此,它只呈现矩形。

    但是,我们可以使用支持希伯来文字符的字体,例如 弗赖桑斯博尔德 . 我们可以通过 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()

    然后生成以下单词cloud:

    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