我的代码:

# -*- 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 可视化 词云图的更多相关文章

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

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

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

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

  3. python 绘制词云图

    1. 先下载并安装nltk包,准备一张简单的图片存入代码所在文件目录,搜集英文停用词表 import nltk nltk.download() 2. 绘制词云图 import re import nu ...

  4. python 做词云图

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

  5. python词云图与中文分词

    2019-12-12中文文本分词和词云图具体功能介绍与学习代码: import jiebaa="由于中文文本的单词不是通过空格或者标点符号来进行分割"#jieba.lcut()s是 ...

  6. (数据科学学习手札71)在Python中制作个性化词云图

    本文对应脚本及数据已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 一.简介 词云图是文本挖掘中用来表征词频的数据可视化 ...

  7. python 爬取豆瓣电影短评并wordcloud生成词云图

    最近学到数据可视化到了词云图,正好学到爬虫,各种爬网站 [实验名称] 爬取豆瓣电影<千与千寻>的评论并生成词云 1. 利用爬虫获得电影评论的文本数据 2. 处理文本数据生成词云图 第一步, ...

  8. 用Python制作酷炫词云图,原来这么简单!

    一.简介词云图是文本挖掘中用来表征词频的数据可视化图像,通过它可以很直观地展现文本数据中地高频词:! 图1 词云图示例 在Python中有很多可视化框架可以用来制作词云图,如pyecharts,但这些 ...

  9. 特朗普退出《巴黎协定》:python词云图舆情分析

    1 前言 2017年6月1日,美国特朗普总统正式宣布美国退出<巴黎协定>.宣布退出<巴黎协定>后,特朗普似乎成了“全球公敌”. 特斯拉总裁马斯克宣布退出总统顾问团队 迪士尼董事 ...

随机推荐

  1. LA 4253 箭术(二分枚举)

    https://vjudge.net/problem/UVALive-4253 题意: 有n个平行于x轴的线段,每条线段代表一个靶子.判断是否可以站在x轴上[0,W]区间内的某个位置射箭. 思路:二分 ...

  2. Matplotlib 练习题

    1. 绘制一个二维随机漫步的图形 直接上代码: %pylab inline nsteps = 1000 draws = np.random.randint(-1,2,size=(2,nsteps)) ...

  3. 关于java中ArrayList的快速失败机制的漏洞——使用迭代器循环时删除倒数第二个元素不会报错

    一.问题描述 话不多说,先上代码: public static void main(String[] args) throws InterruptedException { List<Strin ...

  4. css可应用的渐进增强新特性

    1. 让有滚动行为的元素平滑滚动  scroll-behavior: smooth; <div class="smooth"> </dvi> .smooth ...

  5. Java Spring-AOP中的动态代理

    2017-11-10 16:17:12 AOP中有两种代理方式,分别是JDK的动态代理和CGLib的动态代理. JDK的动态代理 Proxy 提供用于创建动态代理类和实例的静态方法,它还是由这些方法创 ...

  6. ActiveRecord 惰性加载,和使用gem faker

    rails console后: 2.1.4 :001 > User # => User (call 'User.connection' to establish a connection) ...

  7. AndroidStudio怎样导入library项目开源库

    AndroidStudio是一款非常强大的android程序开发软件,在里面集成了几乎所有android开发中需要使用的工具,编译.运行.打包.开发.调试等功能一应俱全,可以使用起来非常方便. 今天要 ...

  8. 使用扩展方法(Chapter3 P39-41)

    namespace LanguageFeatures { public class ShoppingCart { public List<Product> Products { get; ...

  9. IOS UI-标签(Label)的高级应用

    // // BWLabel.h // IOS_0119_label // // Created by ma c on 16/1/19. // Copyright © 2016年 博文科技. All r ...

  10. elasticsearch 自定义similarity 插件开发

    转自:http://www.chepoo.com/elasticsearch-similarity-custom-plug-in-development.html 在搜索开发中,我们要修改打分机制,就 ...