1. 先下载并安装nltk包,准备一张简单的图片存入代码所在文件目录,搜集英文停用词表

import nltk
nltk.download()

2. 绘制词云图

import re
import numpy as np
import pandas as pd
#import matplotlib
import matplotlib.pyplot as plt
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from PIL import Image
from wordcloud import WordCloud
from sklearn.datasets import fetch_20newsgroups
#from sklearn.feature_extraction.text import CountVectorizer
from collections import Counter, defaultdict def word_cut(contents, cut=','):
res = []
for content in contents:
content = content.lower()
words = [word for word in re.split(cut, content) if word]
res.append(words)
return res def word_count(contents):
#words_count = Counter(sum(contents,[])) #慢
word_count_dict = defaultdict(lambda: 0)
for content in contents:
temp_dict = Counter(content)
for key in temp_dict:
word_count_dict[key] += temp_dict[key]
return word_count_dict def stopwords_filter(contents, stopwords):
contents_clean = []
word_count_dict = defaultdict(lambda: 0)
for line in contents:
line_clean = []
for word in line:
if word in stopwords:
continue
line_clean.append(word)
word_count_dict[word] += 1
contents_clean.append(line_clean) words_count = list(word_count_dict.items())
words_count.sort(key=lambda x:-x[1])
words_count = pd.DataFrame(words_count, columns=['word', 'count'])
return contents_clean, words_count # 从外部导入数据
'''
df_news = pd.read_table('val.txt', names=['category','theme','URL','content'], encoding='utf-8')
stopwords = pd.read_csv("stopwords.txt", index_col = False, sep="\t",
quoting=3, names=['stopword'], encoding='utf-8')
contents = df_news.content.values.tolist()
stopwords = stopwords.stopword.values.tolist()''' # 自定义切词
'''
#[ ,.\n\t--\':;?!/+<>@]
#[ ,.\n\t=--\'`_\[\]:;?!^/|+<>{}@~\\]
#contents = word_cut(contents=news.data, cut='[ ,.\n\t-\`_\[\]:;?!\^/|+<>{}@~]')
'''
# 将数据整理为模型入参形式
'''
#vec = CountVectorizer()
#X_train = vec.fit_transform(X_train) #不可直接将vec用在测试集上
#vectorizer_test = CountVectorizer(vocabulary=vec.vocabulary_)
#X_test = vectorizer_test.transform(X_test)
''' # 可从中筛选停用词
'''
word_count_dict = word_count(contents)
temp = list(word_count_dict.items())
temp.sort(key=lambda x:-x[1])
df = pd.DataFrame(temp, columns=['word','count'])
df.to_csv(r'D:\PycharmProjects\zsyb\stop_words.csv')
''' # 调包实现上述功能
news = fetch_20newsgroups(subset='all')
# 自定义的快好几倍,可以加if not in ‘’去标点
contents = [word_tokenize(content.lower()) for content in news.data] #sent_tokenize(content)
punctuations = set(list(',.\n\t-\`_()\[\]:;?!$#%&.*=\^/|+<>{}@~')) #标点
digits = {str(i) for i in range(50)}
others = {'--', "''", '``', "'", '...'}
# 下载网上的停用词表加入 nltk_data\corpora\stopwords,低频词过滤(不要加入停用词)
stopWords = set(stopwords.words('english')) | punctuations | digits | others
contents_clean, words_count = stopwords_filter(contents, stopWords)
#df.groupby(by=['word']).agg({"count": np.size}) # 绘制词云图
fontpath = 'simhei.ttf'
aimask = np.array(Image.open(r"D:\PycharmProjects\zsyb\pig.png")) wc = WordCloud(font_path = fontpath, #设置字体
background_color = "white", #背景颜色
max_words = 1000, #词云显示的最大词数
max_font_size = 100, #字体最大值
min_font_size = 10, #字体最小值
random_state = 42, #随机数
collocations = False, #避免重复单词
mask = aimask, #造型遮盖
width = 1200, height = 800, #图像宽高,需配合plt.figure(dpi=xx)放缩才有效
margin = 2 #字间距
)
word_frequence = {x[0]:x[1] for x in words_count.head(100).values}
word_cloud=wc.fit_words(word_frequence) plt.figure(dpi=100) #通过这里可以放大或缩小
plt.subplot(121)
plt.imshow(aimask)
#plt.axis("off") #隐藏坐标
plt.subplot(122)
plt.imshow(word_cloud)
#plt.axis("off") #隐藏坐标

python 绘制词云图的更多相关文章

  1. Python pyecharts绘制词云图

    一.pyecharts绘制词云图WordCloud.add()方法简介 WordCloud.add()方法简介 add(name,attr,value, shape="circle" ...

  2. python爬虫+词云图,爬取网易云音乐评论

    又到了清明时节,用python爬取了网易云音乐<清明雨上>的评论,统计词频和绘制词云图,记录过程中遇到一些问题 爬取网易云音乐的评论 一开始是按照常规思路,分析网页ajax的传参情况.看到 ...

  3. 使用python绘制词云

    最近在忙考试的事情,没什么时间敲代码,一个月也没几天看代码,最近看到可视化的词云,看到网上也很多这样的工具, 但是都不怎么完美,有些不支持中文,有的中文词频统计得莫名其妙.有的不支持自定义形状.所有的 ...

  4. 使用pyecharts绘制词云图-淘宝商品评论展示

    一.什么是词云图? 词云图是一种用来展现高频关键词的可视化表达,通过文字.色彩.图形的搭配,产生有冲击力地视觉效果,而且能够传达有价值的信息. 制作词云图的网站有很多,简单方便,适合小批量操作. BI ...

  5. python 数据分析--词云图,图形可视化美国竞选辩论

    这篇博客从用python实现分析数据的一个完整过程.以下着重几个python的moudle的运用"pandas",""wordcloud"," ...

  6. python 可视化 词云图

    文本挖掘及可视化知识链接 我的代码: # -*- coding: utf-8 -*- from pandas import read_csv import numpy as np from sklea ...

  7. python 做词云图

    #导入需要模块 import jieba import numpy as np import matplotlib.pyplot as plt from PIL import Image from w ...

  8. Python 绘制词云

    文本内容:data(包含很多条文本) 1.分词: import jieba data_cut = data.apply(jieba.lcut) 2.去除停用词: stoplist.txt:链接:htt ...

  9. 吃瓜的正确姿势,Python绘制罗志祥词云图

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 这篇文章中向大家介绍了Python绘制词云的方法,不难看出绘制词云可以说是一 ...

随机推荐

  1. springmvc的文件上传和JWT图形验证码

    相关pom依赖 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commo ...

  2. R-2 - 正态分布-中心极限-置信区间-正态假设检验

    本节内容 1:样本估计总体均值跟标准差,以及标准误 2:中心极限定理 3:如何查看数据是否是正态分布QQ图 4:置信区间的理解跟案例 5:假设检验 参考文章: 假设检验的学习和理解 一.样本估计总体均 ...

  3. 201871020225-牟星源 《面向对象程序设计(java)》第一周学习总结

    正文 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daiz ...

  4. 2015 经典的ImageCaptioning论文

    1.Show and Tell: A Neural Image Caption Generator Google团队的成果 整体处理流程: 1)通过CNN提取到图片的特征,简称feature. 2)而 ...

  5. 《专访 RocketMQ 联合创始人:项目思路、技术细节和未来规划》

    专访 RocketMQ 联合创始人:项目思路.技术细节和未来规划   木环 阅读数:138092017 年 2 月 20 日 18:00   编者按 这些年开源氛围越来越好,各大 IT 公司都纷纷将一 ...

  6. CSharpGL(54)用基于图像的光照(IBL)来计算PBR的Specular部分

    CSharpGL(54)用基于图像的光照(IBL)来计算PBR的Specular部分 接下来本系列将通过翻译(https://learnopengl.com)这个网站上关于PBR的内容来学习PBR(P ...

  7. Linux 学习记录二(文件的打包压缩).

    和 window不同,在Linux压缩文件需要注意的是,压缩后的文件会把源文件给替代,无论是gzip.bzip2.xz 均不支持压缩目录,要达到压缩目录的目的,需要用到tar指令.   gzip 压缩 ...

  8. 阿里小哥带你玩转JVM:揭秘try-catch-finally在JVM底层都干了些啥?

    让我们准备一个函数:   然后,反编译他的字节码:   首先我们介绍异常表:在编译生成的字节码中,每个方法都附带一个异常表. 异常表中的每一个条目代表一个异常处理器,并且由 from 指针.to 指针 ...

  9. route 相关设置

    Debian系统 查看路由表: root@debian:~# ip route default via 192.168.6.1 dev enp4s0 10.0.0.0/24 dev br0 proto ...

  10. 动态类型dynamic转换为特定类型T的方案

    需求场景:有时候我们抓到一段请求数据,JSON格式的字符串数据,需要放在接口里重现问题,我们就可能会用dynamic先接受数据,然后再转换成特定数据发出请求. 方案一:直接使用特定对象T,来接受请求数 ...