📜  用Python生成词云

📅  最后修改于: 2022-05-13 01:55:31.209000             🧑  作者: Mango

用Python生成词云

词云是一种数据可视化技术,用于表示文本数据,其中每个词的大小表示其频率或重要性。可以使用词云突出显示重要的文本数据点。词云广泛用于分析来自社交网络网站的数据。

为了在Python中生成词云,需要的模块是——matplotlib、pandas 和 wordcloud。要安装这些软件包,请运行以下命令:

pip install matplotlib
pip install pandas
pip install wordcloud

用于生成词云的数据集是从 UCI 机器学习存储库中收集的。它包含 YouTube 对流行艺术家视频的评论。
数据集链接:https://archive.ics.uci.edu/ml/machine-learning-databases/00380/

下面是实现:

Python3
# Python program to generate WordCloud
 
# importing all necessary modules
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import pandas as pd
 
# Reads 'Youtube04-Eminem.csv' file
df = pd.read_csv(r"Youtube04-Eminem.csv", encoding ="latin-1")
 
comment_words = ''
stopwords = set(STOPWORDS)
 
# iterate through the csv file
for val in df.CONTENT:
     
    # typecaste each val to string
    val = str(val)
 
    # split the value
    tokens = val.split()
     
    # Converts each token into lowercase
    for i in range(len(tokens)):
        tokens[i] = tokens[i].lower()
     
    comment_words += " ".join(tokens)+" "
 
wordcloud = WordCloud(width = 800, height = 800,
                background_color ='white',
                stopwords = stopwords,
                min_font_size = 10).generate(comment_words)
 
# plot the WordCloud image                      
plt.figure(figsize = (8, 8), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad = 0)
 
plt.show()


输出 :

上面的词云是使用数据集中的 Youtube04-Eminem.csv 文件生成的。一项有趣的任务可能是使用数据集中可用的其他 csv 文件生成词云。

词云的优点:

  1. 分析客户和员工的反馈。
  2. 确定要定位的新 SEO 关键字。

词云的缺点:

  1. 词云并不适合所有情况。
  2. 数据应针对上下文进行优化。

参考: https ://en.wikipedia.org/wiki/Tag_cloud