python 中具有三个独立值的词云

Word cloud in python with three separate values

我想在 python 中创建一个词云,这样每个词都以数据源的颜色标记 假设我有:

comment         Data source
  Hello there     1  (red)
  Hello!          1  (red) 
  Hi there        2 (green)
  im good         3 (blue)

所以基本上是所有三个评论的词云,其中每个词都是其各自数据源的颜色,所以你好 => 红色,嗨 => 绿色和我,好 => 蓝色。在 'there' 的情况下,对于遇到标签红色和绿色的单词,颜色可能是单独的颜色(比如橙色) 和其他一些颜色,比方说紫色,以防单词出现在蓝色 + 红色标签中,...

如何在 python 中执行相同的操作?我所能做的就是使用以下代码生成一个简单的词云:

from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
wordcloud = WordCloud(
                      stopwords=STOPWORDS,
                      background_color='white',
                      width=1200,
                      height=1000
                     ).generate(word_string)


plt.imshow(wordcloud)
plt.axis('off')
plt.show()

或者可以在画面中简单地做到这一点??

您需要指定一个 color_func 并将其作为关键字参数传递给 Wordcloud。颜色规格需要是有效的 PIL 颜色规格。 一个概念上简单的方法是这样的:

import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS

word_string = ... 

def color_func(word, *args, **kwargs):
    if word in ['hello']:
        color = '#ff0000' # red
    elif word in ['hi']:
        color = '#00ff00' # green
    elif word in ['im', 'good']:
        color = '#0000ff' # blue
    elif word in ['there']:
        color = 'ffa500' # orange
    else:
        color = '#000000' # black
    return color

wc = Wordcloud(..., color_func=color_func, ...)
wc.generate(word_string)

这样写函数有点繁琐,我会定义一个字典将单词映射到颜色,然后将其封装在一个函数中:

word_to_color = dict()

blue_words = ['im', 'good']
for word in blue_words:
    word_to_color[word] = '#0000ff' # blue

# etc

def color_func(word, *args, **kwargs):
    try:
        color = word_to_color[word]
    except KeyError:
        color = = '#000000' # black
    return color

在后一种情况下,您需要确保在定义word_to_color之后定义color_func