如何使用Python从CSV文件生成word cloud

2024-05-16 23:42:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下CSV文件:

    Emoji,CNT,Common
    369,3988,yes
    sosad,2820,yes
    agree,1481,no
    clown,1273,yes
    dead,753,yes
    angry,561,no
    good,404,yes
    agger/dead,317,no
    cry,305,yes
    smile,300,yes

当我搜索相关信息时,它们只有一列。然而,我有一个CSV文件,必须使word云图片。更重要的是,我需要使用上述文件,使更多的信息。如果“公共”列为“是”,则它将显示红色。否则,它将显示黑色

我搜索了很多信息。它们只有一列。然后它们只有一种颜色或随机颜色

因此,我不能做出我尊敬的结果


Tags: 文件csvno信息颜色commonyesgood
2条回答

首先,您需要正确读取此csv文件,只需使用python的pandas库即可做到这一点,如下所示:Reading csv file in python

然后,您可以将python的wordcloud库安装为

pip安装wordcloud

下面是wordcloud的一些好例子https://github.com/amueller/word_cloud#examples

要添加到前面的答案中,这是一个示例代码,可以按照您的要求使用wordcloud库。您需要将CSV拆分为两个字典,一个用于主数据,另一个用于颜色

import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud

# Load data as pandas dataframe
df = pd.read_csv(csv_file_location)

# Create dictionaries out of the dataframe
records = df.to_dict(orient='records')
data = {x['Emoji']: x['CNT'] for x in records}
colors = {x['Emoji']: x['Common'] for x in records}

# Generate word cloud from frequencies
wc = WordCloud(background_color="white", max_words=1000)
wc.generate_from_frequencies(data)

# Color words depending on the colors dictionary
def color_func(word, **kwargs):
    if colors.get(word) == 'yes':
        return "rgb(0, 255, 0)"
    else:
        return "rgb(255, 0, 0)"

wc.recolor(color_func=color_func)

# Show final result
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()

这将为您提供如下图片:

Word cloud

相关问题 更多 >