NLP情感分析和可视化|python实现评论内容的文本清洗、语料库分词、去除停用词、建立TF-IDF矩阵、获取主题词和主题词团

本文主要是介绍NLP情感分析和可视化|python实现评论内容的文本清洗、语料库分词、去除停用词、建立TF-IDF矩阵、获取主题词和主题词团,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 文本数据准备

首先文本数据准备,爬取李佳琦下的评论,如下:

 2 提出文本数据、获得评论内容

#内容读取
import xlrd
import pandas as pdwb=xlrd.open_workbook("评论数据.xlsx")
sh=wb.sheet_by_index(0)
col=sh.ncols
row=sh.nrows
Text=[]
for i in range(row):Text_Context=sh.row_values(i,1,2)[0]Text.append(Text_Context)
del Text[0]
print(Text)

2 进行结巴分词、去除停用词,得到词料

#结巴分词
import jieba
import gensim
#停用词处理import spacy
from spacy.lang.zh.stop_words import STOP_WORDSsent_words = []
for sent0 in Text:try:l=list(jieba.cut(sent0))# print(l)filtered_sentence = []for word in l:if word not in STOP_WORDS:filtered_sentence.append(word)sent_words.append(filtered_sentence)# print( filtered_sentence)except:pass
print(sent_words)
document = [" "

3 生成TF-IDF矩阵:获取逆文档高频词

from sklearn import feature_extraction
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizertfidf_model = TfidfVectorizer().fit(document)
# 得到语料库所有不重复的词
feature = tfidf_model.get_feature_names()
print(feature)
# 得到每个特征对应的id值:即上面数组的下标
print(tfidf_model.vocabulary_)# 每一行中的指定特征的tf-idf值:
sparse_result = tfidf_model.transform(document)# 每一个语料中包含的各个特征值的tf-idf值:
# 每一行代表一个预料,每一列代表这一行代表的语料中包含这个词的tf-idf值,不包含则为空
weight = sparse_result.toarray()# 构建词与tf-idf的字典:
feature_TFIDF = {}
for i in range(len(weight)):for j in range(len(feature)):# print(feature[j], weight[i][j])if feature[j] not in feature_TFIDF:feature_TFIDF[feature[j]] = weight[i][j]else:feature_TFIDF[feature[j]] = max(feature_TFIDF[feature[j]], weight[i][j])
# print(feature_TFIDF)# 按值排序:
print('TF-IDF 排名前十的(TF-IDF>1时):')
featureList = sorted(feature_TFIDF.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)
for i in range(10):print(featureList[i][0], featureList[i][1])k=0
m=0
print('TF-IDF 排名前十的(TF-IDF<1时):')
while k<=10:if featureList[m][1]<1:k+=1print(featureList[m][0], featureList[m][1])m+=1

4 结果:

5 画图

#!/usr/bin/python
# -*- coding:utf-8 -*-from gensim import corpora
from gensim.models import LdaModel
from gensim.corpora import Dictionary
#内容读取
import xlrd
import pandas as pd
from gensim import corpora
from collections import defaultdict
import spacy
from spacy.lang.zh.stop_words import STOP_WORDS
#结巴分词
import jieba
import gensim
#停用词处理wb=xlrd.open_workbook("评论数据.xlsx")
sh=wb.sheet_by_index(0)
col=sh.ncols
row=sh.nrows
Text=[]
for i in range(row):Text_Context=sh.row_values(i,1,2)[0]Text.append(Text_Context)
del Text[0]
print(Text)file1 = open('结巴分词结果.txt','w')sent_word = []
for sent0 in Text:try:l=list(jieba.cut(sent0))sent_word.append(l)# print( filtered_sentence)except:passfor s in sent_word:try:for w in s:file1.write(str(w))file1.write('\n')except:passfile1.close()
sent_words=[]
for l in sent_word:filtered_sentence=[]for word in l:if word not in STOP_WORDS:filtered_sentence.append(word)sent_words.append(filtered_sentence)file2 = open('去除停用词后的结果.txt','w')
for s in sent_word:for w in s:file1.write(w)file2.write('\n')
file2.close()dictionary = corpora.Dictionary(sent_words)
corpus = [dictionary.doc2bow(text) for text in sent_words]
lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=20, passes=60)
# num_topics:主题数目
# passes:训练伦次
# num_words:每个主题下输出的term的数目file3=open("tf-idf值.txt",'w')for topic in lda.print_topics(num_words = 20):try:termNumber = topic[0]print(topic[0], ':', sep='')file3.write(str(topic[0])+':'+''+'\n')listOfTerms = topic[1].split('+')for term in listOfTerms:listItems = term.split('*')print('  ', listItems[1], '(', listItems[0], ')', sep='')file3.write('  '+str(listItems[1])+ '('+str(listItems[0])+ ')',+''+ '\n')except:pass
import pyLDAvis.gensimd=pyLDAvis.gensim.prepare(lda, corpus, dictionary)'''
lda: 计算好的话题模型
corpus: 文档词频矩阵
dictionary: 词语空间
'''pyLDAvis.save_html(d, 'lda_pass10.html')
# pyLDAvis.displace(d) #展示在notebook的output cell中

6 结果展示

 

 

这篇关于NLP情感分析和可视化|python实现评论内容的文本清洗、语料库分词、去除停用词、建立TF-IDF矩阵、获取主题词和主题词团的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/202701

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连