首页 > 其他分享 >电商产品评论数据情感分析

电商产品评论数据情感分析

时间:2023-04-18 22:11:14浏览次数:44  
标签:index word .. neg content 情感 评论 电商 data

# 代码12-1 评论去重的代码
import pandas as pd import re import jieba.posseg as psg import numpy as np

# 去重,去除完全重复的数据 reviews = pd.read_csv("../../data/0404/reviews.csv") reviews = reviews[['content', 'content_type']].drop_duplicates() content = reviews['content']


# 代码12-2 数据清洗
# 去除去除英文、数字等 # 由于评论主要为京东美的电热水器的评论,因此去除这些词语 strinfo = re.compile('[0-9a-zA-Z]|京东|美的|电热水器|热水器|') content = content.apply(lambda x: strinfo.sub('', x))


# 代码12-3 分词、词性标注、去除停用词代码
# 分词 worker = lambda s: [(x.word, x.flag) for x in psg.cut(s)] # 自定义简单分词函数 seg_word = content.apply(worker)
# 将词语转为数据框形式,一列是词,一列是词语所在的句子ID,最后一列是词语在该句子的位置 n_word = seg_word.apply(lambda x: len(x))  # 每一评论中词的个数
n_content = [[x+1]*y for x,y in zip(list(seg_word.index), list(n_word))] index_content = sum(n_content, [])  # 将嵌套的列表展开,作为词所在评论的id
seg_word = sum(seg_word, []) word = [x[0] for x in seg_word]  # 词
nature = [x[1] for x in seg_word]  # 词性
content_type = [[x]*y for x,y in zip(list(reviews['content_type']), list(n_word))] content_type = sum(content_type, [])  # 评论类型
result = pd.DataFrame({"index_content":index_content,                        "word":word,                        "nature":nature,                        "content_type":content_type})
# 删除标点符号 result = result[result['nature'] != 'x']  # x表示标点符号
# 删除停用词 stop_path = open("../../data/0404/stoplist.txt", 'r',encoding='UTF-8') stop = stop_path.readlines() stop = [x.replace('\n', '') for x in stop] word = list(set(word) - set(stop)) result = result[result['word'].isin(word)]
# 构造各词在对应评论的位置列 n_word = list(result.groupby(by = ['index_content'])['index_content'].count()) index_word = [list(np.arange(0, y)) for y in n_word] index_word = sum(index_word, [])  # 表示词语在改评论的位置
# 合并评论id,评论中词的id,词,词性,评论类型 result['index_word'] = index_word



# 代码12-4 提取含有名词的评论
# 提取含有名词类的评论 ind = result[['n' in x for x in result['nature']]]['index_content'].unique() result = result[[x in ind for x in result['index_content']]]

# 代码12-5 绘制词云
import matplotlib.pyplot as plt from wordcloud import WordCloud
frequencies = result.groupby(by = ['word'])['word'].count() frequencies = frequencies.sort_values(ascending = False) # print(frequencies) backgroud_Image=plt.imread('../../data/0404/pl.jpg') wordcloud = WordCloud(font_path="C:/Windows/Fonts/STZHONGS.ttf",                       max_words=100,                       background_color='white',                       mask=backgroud_Image) my_wordcloud = wordcloud.fit_words(frequencies) plt.title('3134',size=20) plt.imshow(my_wordcloud) plt.axis('off') plt.show()
# 将结果写出 result.to_csv("../../data/0404/word.csv", index = False, encoding = 'utf-8')

 

# 代码12-6 匹配情感词

 

import pandas as pd import numpy as np word = pd.read_csv("../../data/0404/word.csv")

 

# 读入正面、负面情感评价词 pos_comment = pd.read_csv("../../data/0404/正面评价词语(中文).txt", header=None,sep="\n",                           encoding = 'utf-8', engine='python') neg_comment = pd.read_csv("../../data/0404/负面评价词语(中文).txt", header=None,sep="\n",                           encoding = 'utf-8', engine='python') pos_emotion = pd.read_csv("../../data/0404/正面情感词语(中文).txt", header=None,sep="\n",                           encoding = 'utf-8', engine='python') neg_emotion = pd.read_csv("../../data/0404/负面情感词语(中文).txt", header=None,sep="\n",                           encoding = 'utf-8', engine='python')

 

# 合并情感词与评价词 positive = set(pos_comment.iloc[:,0])|set(pos_emotion.iloc[:,0]) negative = set(neg_comment.iloc[:,0])|set(neg_emotion.iloc[:,0]) intersection = positive&negative  # 正负面情感词表中相同的词语 positive = list(positive - intersection) negative = list(negative - intersection) positive = pd.DataFrame({"word":positive,                          "weight":[1]*len(positive)}) negative = pd.DataFrame({"word":negative,                          "weight":[-1]*len(negative)})

 

posneg = positive.append(negative)

 

#  将分词结果与正负面情感词表合并,定位情感词 data_posneg = posneg.merge(word, left_on = 'word', right_on = 'word',                            how = 'right') data_posneg = data_posneg.sort_values(by = ['index_content','index_word'])




# 代码12-7 修正情感倾向

 

# 根据情感词前时候有否定词或双层否定词对情感值进行修正 # 载入否定词表 notdict = pd.read_csv("../../data/0404/not.csv")

 

# 处理否定修饰词 data_posneg['amend_weight'] = data_posneg['weight']  # 构造新列,作为经过否定词修正后的情感值 data_posneg['id'] = np.arange(0, len(data_posneg)) only_inclination = data_posneg.dropna()  # 只保留有情感值的词语 only_inclination.index = np.arange(0, len(only_inclination)) index = only_inclination['id']

 

for i in np.arange(0, len(only_inclination)):     review = data_posneg[data_posneg['index_content'] ==                          only_inclination['index_content'][i]]  # 提取第i个情感词所在的评论     review.index = np.arange(0, len(review))     affective = only_inclination['index_word'][i]  # 第i个情感值在该文档的位置     if affective == 1:         ne = sum([i in notdict['term'] for i in review['word'][affective - 1]])         if ne == 1:             data_posneg['amend_weight'][index[i]] = -\             data_posneg['weight'][index[i]]               elif affective > 1:         ne = sum([i in notdict['term'] for i in review['word'][[affective - 1,                   affective - 2]]])         if ne == 1:             data_posneg['amend_weight'][index[i]] = -\             data_posneg['weight'][index[i]]             # 更新只保留情感值的数据 only_inclination = only_inclination.dropna()

 

# 计算每条评论的情感值 emotional_value = only_inclination.groupby(['index_content'],                                            as_index=False)['amend_weight'].sum()

 

# 去除情感值为0的评论 emotional_value = emotional_value[emotional_value['amend_weight'] != 0]




# 代码12-8 查看情感分析效果

 

# 给情感值大于0的赋予评论类型(content_type)为pos,小于0的为neg emotional_value['a_type'] = '' emotional_value['a_type'][emotional_value['amend_weight'] > 0] = 'pos' emotional_value['a_type'][emotional_value['amend_weight'] < 0] = 'neg'

 

# 查看情感分析结果 result = emotional_value.merge(word,                                left_on = 'index_content',                                right_on = 'index_content',                                how = 'left')

 

result = result[['index_content','content_type', 'a_type']].drop_duplicates() confusion_matrix = pd.crosstab(result['content_type'], result['a_type'],                                margins=True)  # 制作交叉表 (confusion_matrix.iat[0,0] + confusion_matrix.iat[1,1])/confusion_matrix.iat[2,2]

 

# 提取正负面评论信息 ind_pos = list(emotional_value[emotional_value['a_type'] == 'pos']['index_content']) ind_neg = list(emotional_value[emotional_value['a_type'] == 'neg']['index_content']) posdata = word[[i in ind_pos for i in word['index_content']]] negdata = word[[i in ind_neg for i in word['index_content']]]

 

# 绘制词云 import matplotlib.pyplot as plt from wordcloud import WordCloud # 正面情感词词云 freq_pos = posdata.groupby(by = ['word'])['word'].count() freq_pos = freq_pos.sort_values(ascending = False) backgroud_Image=plt.imread('../../data/0404/pl.jpg') wordcloud = WordCloud(font_path="C:/Windows/Fonts/STZHONGS.ttf",                       max_words=100,                       background_color='white',                       mask=backgroud_Image) pos_wordcloud = wordcloud.fit_words(freq_pos) plt.imshow(pos_wordcloud) plt.title('3134',size=20) plt.axis('off') plt.show() # 负面情感词词云 freq_neg = negdata.groupby(by = ['word'])['word'].count() freq_neg = freq_neg.sort_values(ascending = False) neg_wordcloud = wordcloud.fit_words(freq_neg) plt.imshow(neg_wordcloud) plt.title('3134',size=20) plt.axis('off') plt.show()

 

# 将结果写出,每条评论作为一行 posdata.to_csv("../../data/0404/posdata.csv", index = False, encoding = 'utf-8') negdata.to_csv("../../data/0404/negdata.csv", index = False, encoding = 'utf-8')  

 

 

# -*- coding: utf-8 -*-

 

# 代码12-9 建立词典及语料库

 

import pandas as pd import numpy as np import re import itertools import matplotlib.pyplot as plt

 

# 载入情感分析后的数据 posdata = pd.read_csv("../../data/0404/posdata.csv", encoding = 'utf-8') negdata = pd.read_csv("../../data/0404/negdata.csv", encoding = 'utf-8')

 

from gensim import corpora, models # 建立词典 pos_dict = corpora.Dictionary([[i] for i in posdata['word']])  # 正面 neg_dict = corpora.Dictionary([[i] for i in negdata['word']])  # 负面

 

# 建立语料库 pos_corpus = [pos_dict.doc2bow(j) for j in [[i] for i in posdata['word']]]  # 正面 neg_corpus = [neg_dict.doc2bow(j) for j in [[i] for i in negdata['word']]]   # 负面




# 代码12-10 主题数寻优

 

# 构造主题数寻优函数 def cos(vector1, vector2):  # 余弦相似度函数     dot_product = 0.0;       normA = 0.0;       normB = 0.0;       for a,b in zip(vector1, vector2):         dot_product += a*b           normA += a**2           normB += b**2       if normA == 0.0 or normB==0.0:           return(None)       else:           return(dot_product / ((normA*normB)**0.5))  

 

# 主题数寻优 def lda_k(x_corpus, x_dict):           # 初始化平均余弦相似度     mean_similarity = []     mean_similarity.append(1)         # 循环生成主题并计算主题间相似度     for i in np.arange(2,11):         lda = models.LdaModel(x_corpus, num_topics = i, id2word = x_dict)  # LDA模型训练         for j in np.arange(i):             term = lda.show_topics(num_words = 50)                     # 提取各主题词         top_word = []         for k in np.arange(i):             top_word.append([''.join(re.findall('"(.*)"',i)) \                              for i in term[k][1].split('+')])  # 列出所有词                     # 构造词频向量         word = sum(top_word,[])  # 列出所有的词           unique_word = set(word)  # 去除重复的词                 # 构造主题词列表,行表示主题号,列表示各主题词         mat = []         for j in np.arange(i):             top_w = top_word[j]             mat.append(tuple([top_w.count(k) for k in unique_word]))                       p = list(itertools.permutations(list(np.arange(i)),2))         l = len(p)         top_similarity = [0]         for w in np.arange(l):             vector1 = mat[p[w][0]]             vector2 = mat[p[w][1]]             top_similarity.append(cos(vector1, vector2))                     # 计算平均余弦相似度         mean_similarity.append(sum(top_similarity)/l)     return(mean_similarity)             # 计算主题平均余弦相似度 pos_k = lda_k(pos_corpus, pos_dict) neg_k = lda_k(neg_corpus, neg_dict)        

 

# 绘制主题平均余弦相似度图形 from matplotlib.font_manager import FontProperties   font = FontProperties(size=14) #解决中文显示问题

 

plt.rcParams['font.sans-serif']=['SimHei'] plt.rcParams['axes.unicode_minus'] = False   fig = plt.figure(figsize=(10,8)) ax1 = fig.add_subplot(211) ax1.plot(pos_k) ax1.set_xlabel('3134', fontproperties=font)

 

ax2 = fig.add_subplot(212) ax2.plot(neg_k) ax2.set_xlabel('3134', fontproperties=font)




# 代码12-11 LDA主题分析

 

# LDA主题分析 pos_lda = models.LdaModel(po

 

 

s_corpus, num_topics = 3, id2word = pos_dict)   neg_lda = models.LdaModel(neg_corpus, num_topics = 3, id2word = neg_dict)   pos_lda.print_topics(num_words = 10)

 

neg_lda.print_topics(num_words = 10)  

 

 

标签:index,word,..,neg,content,情感,评论,电商,data
From: https://www.cnblogs.com/rwc5397/p/17331381.html

相关文章

  • 星起航跨境:亚马逊跨境电商干货分享,有效增加产品曝光的方法
    相信各位亚马逊卖家都遇到过产品曝光量低的问题,很多时候还会因为曝光量低导致销量不理想。那么,卖家应该如何有效提高产品的曝光量呢?星起航在此分享几个有效提高产品曝光量的方法。1、优化产品的标题和描述产品的标题和描述是卖家的产品在亚马逊上给消费者的第一印象,也是消费者在购......
  • [人事管理]评论蜀中为何无大将,看企业人才管理培养机制
    原文引用如下:“蜀中无大将,廖化作先锋”,这句成语所揭示的原本是三国后期蜀汉人才奇缺的历史事实,后来则引伸为泛指因为没有杰出人才,平庸之辈也能侥幸成名,与“山中无老虎,猴子称霸王”意义相近。唐朝的魏元忠说:“何代而不生才,何才而不生代?”进而他说:“士有不用,未有无士之时。”魏元......
  • vivo全球商城:电商交易平台设计
    vivo全球商城:电商交易平台设计 作者:vivo官网商城开发团队-ChengKun、LiuWei本文介绍了交易平台的设计理念和关键技术方案,以及实践过程中的思考与挑战。点击查阅:《vivo全球商城》系列文章一、背景vivo官方商城经过了七年的迭代,从单体架构逐步演进到微服务架构,我们......
  • [技术讨论]电商业务中的业务合并问题
    今天第一次写这个,其实,这些事情在10年前的erp和其他项目中都是有相应的解决方案的。最近在京东采购了两个单子,遇到了下面的问题:1、发过来的衣服是180/100A的,我只能穿175的,申请换货。2、数码相机28exr的取景器内特别模糊,而液晶屏很清晰,我确认不是我眼睛的问题,所以,只能申请换货。京东......
  • 电商购物系统开发的正确步骤是什么?这几个步骤不能忘
     毫不夸张地说,电商购物已经成为当代人们主要的购物方式。在这样的时代背景下,越来越多的企业商家争相开发一个电商购物系统,试图实现盈利。那么电商购物系统开发的正确步骤是什么?下面名锐讯动为大家讲述这几个步骤不能忘。 1.分析市场需求。前面我们说过开发一个电商购物系统的......
  • 2023年饮料电商数据:可口可乐份额下滑,无糖饮料占比40%
    如今,全世界减糖、控糖的大趋势已经拉开帷幕。根据沸点测评数据,今年所有在新加坡销售的饮料,必须在包装上注明A、B、C或D的营养等级标签,列明饮料含糖分和饱和脂肪的百分比,营养等级为D的饮品则会被禁止做广告营销。*截图源于“沸点测评”据了解,有多款国内大众常喝的饮料在新加坡被标为......
  • Hexo博客使用valine评论系统无效果及终极解决方案
    注意事项有一些博主valine评论系统无效果,有一些原因:1、很大程度是因为next的版本升级导致某些参数设置不同2、valine评论是基于LeanCloud,还有一个文章阅读次数功能也是用LeanCloud,两者会有一点冲突之后会给出一些解决方案评论系统选择Hexo可用的评论系统有很多,如下:来必力:https://l......
  • Midjourney魔法解锁:打造电商AI模特,实现无限场景换装
    在网上看到过下图这样一篇《模特不存在了》的帖子:是一个卖内衣的店主,通过Midjourney把石膏模特身上的衣服,穿到了AI生成的模特身上。网上看到的把石膏模特的内衣穿在了AI模特身上可以看到这张图片上左侧的衣服,几乎无差别的穿到了AI模特的身上。但这个帖子没有公布方法和技巧,那......
  • vivo全球商城:电商交易平台设计
    作者:vivo官网商城开发团队-ChengKun、LiuWei本文介绍了交易平台的设计理念和关键技术方案,以及实践过程中的思考与挑战。点击查阅:《vivo全球商城》系列文章一、背景vivo官方商城经过了七年的迭代,从单体架构逐步演进到微服务架构,我们的开发团队沉淀了许多宝贵的技术与经......
  • 电商流量分析怎么做?试试这款数据工具 DataLeap!
    更多技术交流、求职机会,欢迎关注字节跳动数据平台微信公众号,回复【1】进入官方交流群作为成熟的电商模式,货架场景可以让商家以更低的门槛入驻,让消费者完成更高销量的购买和复购。在这一场景下,运营人员每天都需要根据数据来做决策,精准识别每一份流量的效果是最重要的日常运营洞......