了解如何在Python中使用WordCloud对自然语言处理执行探索性数据分析。

最近我们被客户要求撰写关于自然语言处理的研究报告,包括一些图形和统计输出。

什么是WordCloud?

很多时候,您可能会看到一片云,上面堆满了许多大小不同的单词,这些单词代表了每个单词的出现频率或重要性。这称为标签云或词云。对于本教程,您将学习如何在Python中创建自己的WordCloud并根据需要自定义它。

先决条件

numpy库是最流行和最有用的库之一,用于处理多维数组和矩阵。它还与Pandas库结合使用以执行数据分析。

wordcloud安装可能有些棘手。如果您只需要它来绘制基本的wordcloud,则pip install wordcloudconda install -c conda-forge wordcloud就足够了。

git clone https://github.com/amueller/word_cloud.git
cd word_cloud
pip install .

资料集:

首先,您加载所有必需的库:

# Start with loading all necessary libraries
import numpy as np
import pandas as pd
from os import path
from PIL import Image
from wordcloud import WordCloud, STOPWORDS, ImageColorGeneratorimport matplotlib.pyplot as plt
% matplotlib inline
c:\intelpython3\lib\site-packages\matplotlib\__init__.py:
import warnings
warnings.filterwarnings("ignore")

加载数据框。请注意,index_col=0我们没有将行名(索引)作为单独的列读入。

# Load in the dataframe
df = pd.read_csv("data/winemag-data-130k-v2.csv", index_col=0)
# Looking at first 5 rows of the dataset
df.head()

得到打印输出。

print("There are {} observations and {} features in this dataset. \n".format(df.shape[0],df.shape[1]))print("There are {} types of wine in this dataset such as {}... \n".format(len(df.variety.unique()),", ".join(df.variety.unique()[0:5])))print("There are {} countries producing wine in this dataset such as {}... \n".format(len(df.country.unique()),", ".join(df.country.unique()[0:5])))
There are 129971 observations and 13 features in this dataset.There are 708 types of wine in this dataset such as White Blend, Portuguese Red, Pinot Gris, Riesling, Pinot Noir...There are 44 countries producing wine in this dataset such as Italy, Portugal, US, Spain, France...
df[["country", "description","points"]].head()
国家 描述 点数
0 意大利 香气包括热带水果,扫帚,brimston ... 87
1个 葡萄牙 这是成熟果香,柔滑的酒... 87
2 我们 酸和活泼,酸橙果肉的味道和... 87
3 我们 菠萝皮,柠檬髓和橙花... 87
4 我们 就像2012年以来的常规装瓶一样,这... 87

使用groupby()和计算摘要统计信息。

使用葡萄酒数据集,您可以按国家/地区分组并查看所有国家/地区的价格。

这将在所有44个国家/地区中选择前5个最高平均分:

 
点数 价钱
国家
英国 91.581081 51.681159
印度 90.222222 13.333333
奥地利 90.101345 30.762772
德国 89.851732 42.257547
加拿大 89.369650 35.712598

您可以使用Pandas DataFrame和Matplotlib的plot方法按国家/地区对葡萄酒的数量进行绘制。


plt.ylabel("Number of Wines")
plt.show()

在44个生产葡萄酒的国家中,美国的葡萄酒评论数据集中有50,000多种葡萄酒,是排名第二的国家的两倍:法国-以其葡萄酒而闻名的国家。意大利还生产大量优质葡萄酒,有近20,000种葡萄酒可供审查。

数量超过质量吗?

现在,按照评分最高的葡萄酒查看所有44个国家/地区的地块:


plt.ylabel("Highest point of Wines")
plt.show()

澳洲,美国,葡萄牙,意大利和法国都有100分的葡萄酒。如果您注意到,在数据集中生产的葡萄酒数量上,葡萄牙排名第5,澳大利亚排名第9,这两个国家/地区的葡萄酒种类少于8000。

设置基本的WordCloud

使用任何函数之前,您可能要做的第一件事是检出函数的文档字符串,并查看所有必需和可选参数。为此,键入?function并运行它以获取所有信息。

?WordCloud
[1;31mInit signature:[0m [0mWordCloud[0m[1;33m([0m[0mfont_path[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mwidth[0m[1;33m=[0m[1;36m400[0m[1;33m,[0m [0mheight[0m[1;33m=[0m[1;36m200[0m[1;33m,[0m [0mmargin[0m[1;33m=[0m[1;36m2[0m[1;33m,[0m [0mranks_only[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mprefer_horizontal[0m[1;33m=[0m[1;36m0.9[0m[1;33m,[0m [0mmask[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mscale[0m[1;33m=[0m[1;36m1[0m[1;33m,[0m [0mcolor_func[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mmax_words[0m[1;33m=[0m[1;36m200[0m[1;33m,[0m [0mmin_font_size[0m[1;33m=[0m[1;36m4[0m[1;33m,[0m [0mstopwords[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mrandom_state[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mbackground_color[0m[1;33m=[0m[1;34m'black'[0m[1;33m,[0m [0mmax_font_size[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mfont_step[0m[1;33m=[0m[1;36m1[0m[1;33m,[0m [0mmode[0m[1;33m=[0m[1;34m'RGB'[0m[1;33m,[0m [0mrelative_scaling[0m[1;33m=[0m[1;36m0.5[0m[1;33m,[0m [0mregexp[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mcollocations[0m[1;33m=[0m[1;32mTrue[0m[1;33m,[0m [0mcolormap[0m[1;33m=[0m[1;32mNone[0m[1;33m,[0m [0mnormalize_plurals[0m[1;33m=[0m[1;32mTrue[0m[1;33m,[0m [0mcontour_width[0m[1;33m=[0m[1;36m0[0m[1;33m,[0m [0mcontour_color[0m[1;33m=[0m[1;34m'black'[0m[1;33m)[0m[1;33m[0m[0m
[1;31mDocstring:[0m
Word cloud object for generating and drawing.Parameters
----------
font_path : stringFont path to the font that will be used (OTF or TTF).Defaults to DroidSansMono path on a Linux machine. If you are onanother OS or don't have this font; you need to adjust this path.width : int (default=400)Width of the canvas.height : int (default=200)Height of the canvas.prefer_horizontal : float (default=0.90)The ratio of times to try horizontal fitting as opposed to vertical.If prefer_horizontal < 1, the algorithm will try rotating the wordif it doesn't fit. (There is currently no built-in way to get onlyvertical words.)mask : nd-array or None (default=None)If not None, gives a binary mask on where to draw words. If mask is notNone, width and height will be ignored, and the shape of mask will beused instead. All white (#FF or #FFFFFF) entries will be considered"masked out" while other entries will be free to draw on. [Thischanged in the most recent version!]contour_width: float (default=0)If mask is not None and contour_width > 0, draw the mask contour.contour_color: color value (default="black")Mask contour color.scale : float (default=1)Scaling between computation and drawing. For large word-cloud images,using scale instead of larger canvas size is significantly faster, butmight lead to a coarser fit for the words.min_font_size : int (default=4)Smallest font size to use. Will stop when there is no more room in thissize.font_step : int (default=1)Step size for the font. font_step > 1 might speed up computation butgive a worse fit.max_words : number (default=200)The maximum number of words.stopwords : set of strings or NoneThe words that will be eliminated. If None, the build-in STOPWORDSlist will be used.background_color : color value (default="black")Background color for the word cloud image.max_font_size : int or None (default=None)Maximum font size for the largest word. If None, the height of the image isused.mode : string (default="RGB")Transparent background will be generated when mode is "RGBA" andbackground_color is None.relative_scaling : float (default=.5)Importance of relative word frequencies for font-size.  Withrelative_scaling=0, only word-ranks are considered.  Withrelative_scaling=1, a word that is twice as frequent will have twicethe size.  If you want to consider the word frequencies and not onlytheir rank, relative_scaling around .5 often looks good... versionchanged: 2.0Default is now 0.5.color_func : callable, default=NoneCallable with parameters word, font_size, position, orientation,font_path, random_state that returns a PIL color for each word.Overwrites "colormap".See colormap for specifying a matplotlib colormap instead.regexp : string or None (optional)Regular expression to split the input text into tokens in process_text.If None is specified, ``r"\w[\w']+"`` is used.collocations : bool, default=TrueWhether to include collocations (bigrams) of two words... versionadded: 2.0colormap : string or matplotlib colormap, default="viridis"Matplotlib colormap to randomly draw colors from for each word.Ignored if "color_func" is specified... versionadded: 2.0normalize_plurals : bool, default=TrueWhether to remove trailing 's' from words. If True and a wordappears with and without a trailing 's', the one with trailing 's'is removed and its counts are added to the version withouttrailing 's' -- unless the word ends with 'ss'.Attributes
----------
``words_`` : dict of string to floatWord tokens with associated frequency... versionchanged: 2.0``words_`` is now a dictionary``layout_`` : list of tuples (string, int, (int, int), int, color))Encodes the fitted word cloud. Encodes for each word the string, fontsize, position, orientation, and color.Notes
-----
Larger canvases will make the code significantly slower. If you need a
large word cloud, try a lower canvas size, and set the scale parameter.The algorithm might give more weight to the ranking of the words
then their actual frequencies, depending on the ``max_font_size`` and the
scaling heuristic.
[1;31mFile:[0m           c:\intelpython3\lib\site-packages\wordcloud\wordcloud.py
[1;31mType:[0m           type

您可以看到WordCloud对象唯一需要的参数是text,而所有其他参数都是可选的。

因此,让我们从一个简单的示例开始:使用第一个观察描述作为wordcloud的输入。三个步骤是:

  • 提取评论(文本文件)
  • 创建并生成wordcloud图像
  • 使用matplotlib显示云
# Display the generated image:
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

您可以看到第一篇评论提到了很多关于葡萄酒的香气。

现在,改变WordCloud像一些可选参数max_font_sizemax_wordbackground_color


plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()

如果要保存图像,WordCloud提供了一个功能 to_file

# Save the image in the img folder:
wordcloud.to_file("img/first_review.png")
<wordcloud.wordcloud.WordCloud at 0x16f1d704978>

将它们加载到其中时,结果将如下所示:

因此,现在您将所有葡萄酒评论合并为一个大文本,并创建一个巨大的胖云,以查看这些葡萄酒中最常见的特征。

print ("There are {} words in the combination of all review.".format(len(text)))
There are 31661073 words in the combination of all review.

# Display the generated image:
# the matplotlib way:
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

哦,似乎黑樱桃和浓郁的醇厚是最受欢迎的特征,而赤霞珠则是最受欢迎的特征。这与赤霞珠“是世界上最广为人知的红酒葡萄品种之一。

现在,让我们将这些话倒入一杯葡萄酒中!

为了为您的wordcloud创建形状,首先,您需要找到一个PNG文件以成为遮罩。以下是一个不错的网站,可以在Internet上找到它:

为了确保遮罩能够正常工作,让我们以numpy数组形式对其进行查看:


array([[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],...,[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 0, 0]], dtype=uint8)

首先,使用该transform_format()函数将数字0交换为255。

def transform_format(val):if val == 0:return 255else:return val

然后,创建一个形状与您现有的蒙版相同的新蒙版,并将该功能transform_format()应用于上一个蒙版的每一行中的每个值。

现在,您将以正确的形式创建一个新的蒙版。

array([[255, 255, 255, ..., 255, 255, 255],[255, 255, 255, ..., 255, 255, 255],[255, 255, 255, ..., 255, 255, 255],...,[255, 255, 255, ..., 255, 255, 255],[255, 255, 255, ..., 255, 255, 255],[255, 255, 255, ..., 255, 255, 255]])

好的!使用正确的蒙版,您可以开始使用选定的形状制作wordcloud。


# show
plt.figure(figsize=[20,10])
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()

创建了一个酒瓶形状的wordcloud!似乎葡萄酒描述中最常提及的是黑樱桃,水果风味和葡萄酒的浓郁特性。现在,让我们仔细看看每个国家/地区的评论:

按照颜色图案创建wordcloud

可以合并五个拥有最多葡萄酒的国家的所有评论。要查找这些国家/地区,可以查看地块国家/地区与上方的葡萄酒数量的关系,也可以使用上方的组来查找每个国家/地区(每个组)的观察数量,并sort_values()使用参数ascending=False降序排列。

country
US          54504
France      22093
Italy       19540
Spain        6645
Portugal     5691
dtype: int64

因此,现在您有5个热门国家/地区:美国,法国,意大利,西班牙和葡萄牙。

country
US           54504
France       22093
Italy        19540
Spain         6645
Portugal      5691
Chile         4472
Argentina     3800
Austria       3345
Australia     2329
Germany       2165
dtype: int64

目前,仅5个国家就足够了。

要获得每个国家/地区的所有评论,您可以使用" ".join(list)语法将所有评论连接起来,该语法将所有元素合并在以空格分隔的列表中。


然后,如上所述创建wordcloud。


# store to file
plt.savefig("img/us_wine.png", format="png")plt.show()

看起来不错!现在,让我们再重复一次法国的评论。


# store to file
plt.savefig("img/fra_wine.png", format="png")#plt.show()

请注意,绘图后应保存图像,以使单词云具有所需的颜色模式。


# store to file
plt.savefig("img/ita_wine.png", format="png")#plt.show()

继意大利之后是西班牙:


# store to file
plt.savefig("img/spa_wine.png", format="png")
#plt.show()

最后,葡萄牙:


# store to file
plt.savefig("img/por_wine.png", format="png")
#plt.show()

最终结果在下表中。

在Python中自然语言处理生成词云WordCloud相关推荐

  1. 导出微信聊天记录,使用python进行分词,生成词云

    导出微信聊天记录,使用python进行分词,生成词云 导出微信聊天记录,使用python进行分词,生成词云 备份数据 浏览.导出数据 查看数据 操作数据库,分析生成词云 下载全部文件 导出微信聊天记录 ...

  2. Py之wordcloud:python中非常有趣的词云图wordcloud简介、安装、使用方法、案例应用详细攻略

    Py之wordcloud:python中非常有趣的词云图wordcloud简介.安装.使用方法.案例应用详细攻略 目录 wordcloud简介 wordcloud安装 wordcloud使用方法 案例 ...

  3. python官网中cloudword在哪_Py之wordcloud:python中非常有趣的词云图wordcloud简介、安装、使用方法...

    Py之wordcloud:python中非常有趣的词云图wordcloud简介.安装.使用方法.案例应用详细攻略 目录 wordcloud简介 构建词云的方法很多, 但是个人觉得python的word ...

  4. Python 任意中文文本生成词云 最终版本

    前叙 利用下面的代码你将可以将任意中文文本生成词云,其分词部分由jieba,NLPIR2016两个部分组成,生成词语由worldcloud负责,默认会自动发现文本中的20个新词并添加到词库中,当然你也 ...

  5. python爬取数据生成词云_Python 爬取生成中文词云以爬取知乎用户属性为例

    代码如下: # -*- coding:utf-8 -*- import requests import pandas as pd import time import matplotlib.pyplo ...

  6. 用python生成词云wordcloud

    代码如下: import wordcloudimport jiebaexcludes={"将军","却说","二人","不可&qu ...

  7. 用python生成云词汇_用python生成词云wordcloud

    代码如下: import wordcloud import jieba excludes={"将军","却说","二人","不可& ...

  8. python生成的词云没有图案_Python生成词云的实现代码

    1 概述 利用Python生成简单的词云,需要的工具是cython,wordcloud与anaconda. 2 准备工作 包括安装cython,wordcloud与anaconda. 2.1 安装an ...

  9. 如何使用python生成词云并透明背景的词云?

    首先是我们需要用到的两个库,一个是wordcloud用于生成词云,还有一个是jieba(外号:结巴)用于进行中文的分词,如果你制作的图云中不包含中文,那么可以不用下载结巴. 环境报错解决思路 如果你是 ...

最新文章

  1. 【跃迁之路】【707天】程序员高效学习方法论探索系列(实验阶段464-2019.1.28)...
  2. 错误处理:Syntax error: Bad for loop variable
  3. fan怎么写 jin_拼音为fan的字
  4. python 可视化 画直线_用Python画江苏省地图,实现各地级市数据可视化
  5. Python连接Oracle-常见问题
  6. [转载]Qt之获取本机网络信息_vortex_新浪博客
  7. 计算机数值转换教案,计算机数值方法教案.doc
  8. SLAM入门-相机成像原理与公式推导
  9. 2022DIY电脑配置入门篇(包含各cpu显卡天梯图对比)
  10. 人工智能python编程训练营_贪心科技 人工智能 Python 编程特训营 第四个主题项目代码...
  11. 为什么4万月薪招聘不到赴日软件工程师?
  12. mysql错误:Can’t create TCP/IP socket (10106) 解决方法
  13. 零基础Python爬虫实现(百度贴吧)
  14. 2016苹果开发者账号注册申请流程链接
  15. python图书销售系统
  16. JavaPoet使用详解
  17. UE4动画重定向与动画蒙太奇(播放动画)
  18. 脸部识别是根据什么识别的_我们需要知道面部识别失败的频率
  19. Chromium浏览器启动参数
  20. android singleTask

热门文章

  1. python画三瓣树叶_python教你画一棵树
  2. 计算机网络应用押韵句,沙雕押韵很可爱的rap的句子 笑掉大牙的押韵句子
  3. 孟岩:算力是新数字经济的支点,去中心化网络资产规模将达10万亿美元
  4. 【交往智慧】004.己所不欲,勿施于人
  5. mac 安装python并切换到python3版本
  6. 教你如何用路由器连接网页登陆式校园网(by liukun321 咕唧咕唧)
  7. 微软官方原版win7(64位/32位)旗舰版系统下载
  8. android studio assets 添加,Android studio 添加assets文件夹的方法
  9. 【译】创意编码之噪音
  10. 一个开发者自述:我是如何设计针对冷热读写场景的 RocketMQ 存储系统