首页 > 解决方案 > 带有字符串列表的列中的文本的 Wordcloud

问题描述

我的数据集有 10 列,其中一列有文本作为字符串列表。

数据集:

Col1 Col2 Col3 Text
...   ...  ... ['I','have', 'a','dream']
...   ...  ... ['My', 'mom', 'is','Spanish']

编码

wordcloud = WordCloud(stopwords=stopwords, max_font_size=50, max_words=100, background_color="white").generate(' '.join(df['Text']))
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()

返回

TypeError: sequence item 0: expected str instance, list found

很明显,它需要字符串,而不是列表。如何在字符串中转换 Text 列中的列表?

标签: pythonpandasword-cloud

解决方案


您可以尝试先用 连接列中的列表df['Text'].sum()然后加入:

combined_text = ' '.join(df['Text'].sum())

wordcloud = (
    WordCloud(stopwords=stopwords, 
              max_font_size=50, 
              max_words=100,       
              background_color="white")
    .generate(combined_text)
)

推荐阅读