【问题标题】:Generate WordCloud from multiple sets of text从多组文本生成 WordCloud
【发布时间】:2016-04-25 13:28:38
【问题描述】:

基于这个问题How to create a word cloud from a corpus in Python?,我使用amueller's 库构建了一个词云。但是,我看不到如何为云提供多个文本集。到目前为止,这是我尝试过的:

wc = WordCloud(background_color="white", max_words=2000, mask=alice_mask,
               stopwords=STOPWORDS.add("said"))
wc.generate(set_of_words)
wc.generate("foo") # this overwrites the previous line of code
# but I would like this to be appended to the set of words

我找不到该库的任何手册,所以我不知道如何进行,是吗? :)


实际上,正如你在这里看到的:Dictionary with array of different types as value in Python,我有这个数据结构:

category = {  "World news": [2, "foo bla content of", "content of 2nd article"],
              "Politics": [1, "only 1 article here"],
              ...
}

我想将“foo bla content of”和“content of 2nd article”附加到世界云。

【问题讨论】:

  • 为什么不将任何单词附加到原始集,然后生成扩展集?在某个点之后,它的计算成本会很高,但这是一个问题吗?
  • @NBartley 我有一本字典,其中每个键都有多个值,每个值都是多个单词。我想附加前 5 个键的所有单词,但我不知道该怎么做。我是 Python 新手。
  • 您能否提供一些详细说明此问题的代码?目前尚不清楚您的set_of_words 是什么数据结构。
  • 哦@NBartley 非常抱歉,我以为我有更新,请查看我更新的问题。

标签: python word-cloud


【解决方案1】:

最简单的解决方案是使用更新的语料库重新生成 wordcloud。

要使用包含在 category 数据结构中的文本(适用于所有主题)构建语料库,您可以使用以下理解:

# Update the corpus
corpus = " ".join([" ".join(value[1:]) for value in category.values()])
# Regenerate the word cloud
wc.generate(corpus)

为数据结构中的单个键构建词云(例如政治):

# Update the corpus
corpus = " ".join(category["Politics"][1:])
# Regenerate the word cloud
wc.generate(corpus)

解释:

  • join 将多个字符串粘合在一起,由给定的分隔符分隔
  • [1:] 获取列表中除第一个之外的所有元素
  • dict.values() 给出字典中所有值的列表

表达式" ".join([" ".join(value[1:]) for value in category.values()])因此可以翻译为:

首先将除第一个键之外的每个键的所有元素粘合在一起(因为它是一个计数器)。然后将所有生成的字符串粘在一起。

【讨论】:

  • 我只想为一个密钥构建云,而不是为所有密钥构建云。我认为您的代码没有这样做?还有一点解释你的第一行做了什么会很好。
【解决方案2】:

https://github.com/amueller/word_cloud/blob/master/wordcloud/wordcloud.py 中的类的简短浏览来看,没有更新方法,因此您需要重新生成 wordcloud 或添加更新方法。

最简单的方法可能是保留原始源文本,并添加到它的末尾,然后重新生成。

【讨论】:

  • 感谢刘易斯的回答,我看到了def update(self, img_array, pos_x, pos_y):,这有帮助吗?
  • @gsamaras - 这不适用于 WordCloud 类
  • 他得到了整理很好,所以我会给刘易斯+1。
猜你喜欢
  • 2021-02-14
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-14
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
相关资源
最近更新 更多