基于这个问题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 内容”和“第二篇文章的内容”。
最佳答案
最简单的解决方案是使用更新后的语料库重新生成词云。
要使用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() 给出字典中所有值的列表
对于category.values()])中的值,表达式"".join(["".join(value[1:]))
因此可以翻译为:
首先将每个键的所有元素粘合在一起,除了第一个元素(因为它是一个计数器)。然后将所有生成的字符串粘合在一起。
关于python - 从多组文本生成WordCloud,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34887551/