python 可视化 词云图
我的代码:
# -*- coding: utf-8 -*-
from pandas import read_csv
import numpy as np
from sklearn.datasets.base import Bunch
import pickle # 导入cPickle包并且取一个别名pickle #持久化类
from sklearn.feature_extraction.text import TfidfVectorizer
import jieba
import operator # 排序用
from sklearn import metrics
from sklearn.externals import joblib
import xlwt
#导入wordcloud模块和matplotlib模块
import wordcloud
import matplotlib.pyplot as plt
from scipy.misc import imread '''读取停用词'''
def _readfile(path):
with open(path, "rb") as fp:
content = fp.read()
return content ''' 读取bunch对象''' def _readbunchobj(path):
with open(path, "rb") as file_obj:
bunch = pickle.load(file_obj)
return bunch '''写入bunch对象''' def _writebunchobj(path, bunchobj):
with open(path, "wb") as file_obj:
pickle.dump(bunchobj, file_obj) def buildtestbunch(bunch_path, art_test):
bunch = Bunch(contents=[])#label=[],
# =============================================================================
# for item1 in testlabel:
# bunch.label.append(item1)
# ============================================================================= # testContentdatasave=[] #存储所有训练和测试数据的分词
for item2 in art_test:
item2 = str(item2)
item2 = item2.replace("\r\n", "")
item2 = item2.replace(" ", "")
content_seg = jieba.cut(item2)
save2 = ''
for item3 in content_seg:
if len(item3) > 1 and item3 != '\r\n':
# testContentdatasave.append(item3)
save2 = save2 + "," + item3
bunch.contents.append(save2)
with open(bunch_path, "wb") as file_obj:
pickle.dump(bunch, file_obj)
print("构建测试数据文本对象结束!!!") def vector_space(stopword_path, bunch_path, space_path):
stpwrdlst = _readfile(stopword_path).splitlines() # 读取停用词
bunch = _readbunchobj(bunch_path) # 导入分词后的词向量bunch对象
# 构建tf-idf词向量空间对象
tfidfspace = Bunch(label=bunch.label, tdm=[], vocabulary={}) # 权重矩阵tdm,其中,权重矩阵是一个二维矩阵,tdm[i][j]表示,第j个词(即词典中的序号)在第i个类别中的IF-IDF值 # 使用TfidVectorizer初始化向量空间模型
vectorizer = TfidfVectorizer(stop_words=stpwrdlst, sublinear_tf=True, max_df=0.5, min_df=0.0001, use_idf=True,
max_features=15000)
# print(vectorizer)
# 文本转为词频矩阵,单独保存字典文件
tfidfspace.tdm = vectorizer.fit_transform(bunch.contents)
tfidfspace.vocabulary = vectorizer.vocabulary_
# 创建词袋的持久化
_writebunchobj(space_path, tfidfspace)
print("if-idf词向量空间实例创建成功!!!") def testvector_space(stopword_path, bunch_path, space_path, train_tfidf_path):
stpwrdlst = _readfile(stopword_path).splitlines() # 把停用词变成列表
bunch = _readbunchobj(bunch_path)
tfidfspace = Bunch(tdm=[], vocabulary={})#label=bunch.label,
# 导入训练集的TF-IDF词向量空间 ★★
trainbunch = _readbunchobj(train_tfidf_path)
tfidfspace.vocabulary = trainbunch.vocabulary vectorizer= TfidfVectorizer(stop_words=stpwrdlst, sublinear_tf=True, max_df=0.7, vocabulary=trainbunch.vocabulary,
min_df=0.001) tfidfspace.tdm = vectorizer.fit_transform(bunch.contents)
_writebunchobj(space_path, tfidfspace)
print("if-idf词向量空间实例创建成功!!!") if __name__=="__main__": Sdata = []
art = []
'''============================先导入数据=================================='''
file_test = 'F:/goverment/text analyse/type_in.csv' dataset = read_csv(file_test)
Sdata = dataset.values[:, :]
Sdata=Sdata.tolist()
for line in Sdata:
art.append(line[1])#line[1]为文本
print(len(Sdata)) '''==========================================================tf-idf对Bar进行文本特征提取============================================================================'''
# 导入分词后的词向量bunch对象
test_bunch_path = "F:/goverment/text analyse/trainbunch.bat"
test_space_path = "F:/goverment/text analyse/traintfdifspace.dat"
stopword_path = "F:/goverment/text analyse/hlt_stop_words.txt" '''============================================================tf-idf对Sart进行文本特征提取==============================================================================''' buildtestbunch(test_bunch_path, art) testvector_space(stopword_path, test_bunch_path, test_space_path, test_space_path) test_set = _readbunchobj(test_space_path) '''测试数据''' #获取已知 id 找 文本
txtcut=[] #存放所有词
dic={}
for i in test_set.vocabulary.keys():
txtcut.append(i)
dic[test_set.vocabulary[i]]=i #print(dic) #print(test_set.tdm)
#print(test_set.tdm[0])
#print(dir(test_set))
#print(test_set.vocabulary)
#print(dir(test_set.tdm)) #print(Sdata) #print(nonzero[1]) '''final里放的是不超过15的词'''
#print(Sdata)
final=[]
for k in range(len(Sdata)):#遍历每一条文本
nonzero=test_set.tdm[k].nonzero()
ls=[]
ls.append(Sdata[k][0])
num=0
for i in range(len(nonzero[1])):
num=num+1
b=test_set.tdm[k, nonzero[1][i]]*100 #test_set.tdm[k, nonzero[1][i]]是第k条文本中,第i个权重非零的词权重
a= dic[nonzero[1][i]] +" "+str(round(b,2))+"%"
ls.append(a)
if num==15:
break
final.append(ls) '''画词云图'''
fig = plt.figure(figsize = (15,15))
cloud = wordcloud.WordCloud(font_path='STXINGKA.TTF',mask=imread('water3.png'),mode='RGBA',
background_color=None).generate(' '.join(txtcut))
img = imread('water3.png')
cloud_colors = wordcloud.ImageColorGenerator(np.array(img))
cloud.recolor(color_func=cloud_colors)
plt.imshow(cloud)
plt.axis('off')
plt.savefig('watercloud3.png',dpi=400)
plt.show() myexcel = xlwt.Workbook()
sheet = myexcel.add_sheet("sheet1")
si=-1
sj=-1
for line in final:
si=si+1
sj=-1
for i in line:
sj=sj+1
sheet.write(si,sj,str(i)) myexcel.save("各条分词.xls") #把id存好
myexcel = xlwt.Workbook()
sheet = myexcel.add_sheet("sheet2")
p=0
for i in test_set.vocabulary.keys():
sheet.write(p,0,i)
print(i)
sheet.write(p,1,str(test_set.vocabulary[i]))
p=p+1 myexcel.save("词汇id.xls")
各条分词:
词汇id:
python 可视化 词云图的更多相关文章
- python 数据分析--词云图,图形可视化美国竞选辩论
这篇博客从用python实现分析数据的一个完整过程.以下着重几个python的moudle的运用"pandas",""wordcloud"," ...
- python爬虫+词云图,爬取网易云音乐评论
又到了清明时节,用python爬取了网易云音乐<清明雨上>的评论,统计词频和绘制词云图,记录过程中遇到一些问题 爬取网易云音乐的评论 一开始是按照常规思路,分析网页ajax的传参情况.看到 ...
- python 绘制词云图
1. 先下载并安装nltk包,准备一张简单的图片存入代码所在文件目录,搜集英文停用词表 import nltk nltk.download() 2. 绘制词云图 import re import nu ...
- python 做词云图
#导入需要模块 import jieba import numpy as np import matplotlib.pyplot as plt from PIL import Image from w ...
- python词云图与中文分词
2019-12-12中文文本分词和词云图具体功能介绍与学习代码: import jiebaa="由于中文文本的单词不是通过空格或者标点符号来进行分割"#jieba.lcut()s是 ...
- (数据科学学习手札71)在Python中制作个性化词云图
本文对应脚本及数据已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 一.简介 词云图是文本挖掘中用来表征词频的数据可视化 ...
- python 爬取豆瓣电影短评并wordcloud生成词云图
最近学到数据可视化到了词云图,正好学到爬虫,各种爬网站 [实验名称] 爬取豆瓣电影<千与千寻>的评论并生成词云 1. 利用爬虫获得电影评论的文本数据 2. 处理文本数据生成词云图 第一步, ...
- 用Python制作酷炫词云图,原来这么简单!
一.简介词云图是文本挖掘中用来表征词频的数据可视化图像,通过它可以很直观地展现文本数据中地高频词:! 图1 词云图示例 在Python中有很多可视化框架可以用来制作词云图,如pyecharts,但这些 ...
- 特朗普退出《巴黎协定》:python词云图舆情分析
1 前言 2017年6月1日,美国特朗普总统正式宣布美国退出<巴黎协定>.宣布退出<巴黎协定>后,特朗普似乎成了“全球公敌”. 特斯拉总裁马斯克宣布退出总统顾问团队 迪士尼董事 ...
随机推荐
- Linux 用户和组的 添加/删除
1.建用户:adduser phpq //新建phpq用户passwd phpq //给phpq用户设置密码 2.建工作组groupadd test //新建test工作组 3.新建用户同时增加工作组 ...
- python 单向链表
import sys import random class employee: def __init__(self): self.num= self.salary= self.name='' sel ...
- Android ViewGroup等容器控件的使用
在Android中,可以自定义类,继承ViewGroup等容器类,以实现自己需要的布局显示.如果你在ViewGroup中增加了控件,却无法显示出 来,那么下面这个例子,就可以用来参考了.(主要是要实现 ...
- 前端引用公共html模块方案
最近临时一个负责公司官网的妹纸请假,于是临时接手了下官网的项目,官网都是静态页面,算是很简单的,但发现页面挺多,而每个页面总有部分是和其他页面一模一样的,比如页头.页尾等,这样就导致一个地方的修改要在 ...
- ElasticSearch安装和head插件安装
本文主要介绍elasticsearch5.0安装及head插件安装.确保系统已经安装好jdk1.8以上,操作系统CentOS6以上. 一.elasticsearch安装配置 1.官网下载源码包 下载不 ...
- Java中HashMap的put与get方法原理
直接上代码 注: 代码来自于 Java 9 put方法 public V put(K key, V value) { return putVal(hash(key), key, value, fals ...
- Rails 5 Test Prescriptions 第14章 Testing Exteranl Services(中断。)
external testing strategy ✅ the service integration test✅ introduce VCR✅ Client Unit Tests ❌ Why an ...
- 最全Python内置函数
内置函数的基本使用 abs的使用: 取绝对值 absprint(abs(123))print(abs(-123)) result:123123 all的使用: 循环参数,如果每个元素都为真的情况下,那 ...
- git源代码管理工具
git是一款源代码管理工具 是分布式版本管理工具 分布式管理必须先在本地提交然后才能提交到服务器: svn集中式版本管理工具 集中式版本管理工具离开服务器就做不了版本管理: 初始化仓库 1.用git初 ...
- hadoop安装及注意事项
一.hadoop安装及注意事项1.安装hadoop的环境,必须在你的系统中有java的环境.2.必须安装ssh,有的系统默认就安装,如果没有安装需要手动安装. 可以用yum install -y ...