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

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

时间:2023-04-04 16:26:07浏览次数:23  
标签:index csv word content 情感 评论 result 电商 type

import pandas as pd
import re
import jieba.posseg as psg
import numpy as np


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

 

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

 


# 分词
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("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)
backgroud_Image=plt.imread('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.imshow(my_wordcloud)
plt.axis('off')
plt.show()

# 将结果写出
result.to_csv("word.csv", index = False, encoding = 'utf-8')

 

 

 

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

# 读入正面、负面情感评价词
pos_comment = pd.read_csv("正面评价词语(中文).txt", header=None,sep="\n",
encoding = 'utf-8', engine='python')
neg_comment = pd.read_csv("负面评价词语(中文).txt", header=None,sep="\n",
encoding = 'utf-8', engine='python')
pos_emotion = pd.read_csv("正面情感词语(中文).txt", header=None,sep="\n",
encoding = 'utf-8', engine='python')
neg_emotion = pd.read_csv("负面情感词语(中文).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'])

 

# 根据情感词前时候有否定词或双层否定词对情感值进行修正
# 载入否定词表
notdict = pd.read_csv("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]

 

# 给情感值大于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('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.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.axis('off')
plt.show()

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

 

标签:index,csv,word,content,情感,评论,result,电商,type
From: https://www.cnblogs.com/Nothingtolose/p/17286791.html

相关文章

  • 电商-产品推广中如何介入付费
    目录前言一阶段基础数据打造二阶段产品入池三阶段拉新和收割闭环路线一:直通车放大路线二:万相台拉新快介入路线三:引力魔方拉新路线四:综合推广四阶段拉新与收割闭环推荐流量前言2023年第一个季度,最大的感受就是补单风险不断地提高,多方都反馈存在补单就降权的情况。分析原因不......
  • 电商产品评论数据情感分析
    针对用户在电商平台上留下的评论数据,对其进行分词、词性标注和去除停用词等文本预处理。基于预处理后的数据进行情感分析,并使用LDA主题模型提取评论关键信息,以了解用户的需求、意见、购买原因及产品的优缺点等,最终提出改善产品的建议。数据预处理评论去重避免一些客户长时间不......
  • API获取商品评论?
    前言   小伙伴们好,前两天因为个人原因耽误了内容的更新,在这里和所有的小伙伴道个歉,今天CC和大家唠唠商品评论的这个话题,大家在网上购物的决策会因为《商品评论的好坏》吗,相信绝大的一部分的小伙伴都不用思考,脑袋里就直接蹦出来一句,肯定啊,肯定要根据其他买家的用户体验去决定......
  • 大数据带来新机遇:如何利用大数据技术优化跨境电商运营?
    互联网和电商的不断发展,跨境电商已经成为一种全新的商业模式。然而,跨境电商的运营需要面对很多挑战,如物流、支付、语言文化等。如何利用大数据技术优化跨境电商运营成为一个重要的课题。一、大数据技术在跨境电商中的应用数据挖掘数据挖掘是大数据技术的核心之一,它可以对跨......
  • 跨境电商时代的“智慧引擎”:探索大数据如何推动跨境电商发展
    如今跨境电商成为了国际贸易领域的一个新热点,而大数据技术的应用,则为跨境电商的发展提供了强大的助力。本文将从大数据的角度探讨如何推动跨境电商的发展,以及大数据技术在跨境电商中的应用。 一、大数据与跨境电商随着全球化的加速,跨境电商已成为全球贸易的一部分。跨境电商......
  • magento 在产品页添加评论 Add Review Form in Magento Product View Page
    Magento产看产品评论需要点击到另外一个页面中,这种设计对于用户体验和SEO都相当不利。一方面用户无法在产品页面查看该产品的一些用户评价,另外,搜索引擎也会收录很多与产品无关的页面。那么如何让产品评论直接显示在产品页面呢?我们需要修改一下模板文件,很简单即可实现。 首先,在lay......
  • 印度最大电商网站Flipkart新增预付钱包功能
    近日,被称为“印度的亚马逊”的印度最大电子商务网站Flipkart为其平台新增了预付钱包功能。通过该功能,用户可在其网站上预存一定金额的钱,避免每次网购都需输入信用卡信息的麻烦,既快捷又安全。Flipkart成立于2007年,创始人Sachin和BinnyBansal均是亚马逊的前雇员。Flipkart是印度......
  • 评论数据分析
    #-*-coding:utf-8-*-#代码12-1评论去重的代码importpandasaspdimportreimportjieba.possegaspsgimportnumpyasnp#去重,去除完全重复的数据reviews=pd.read_csv("C:/Users/admin/Downloads/data/reviews.csv")reviews=reviews[['content','conte......
  • 新手如何使用Tiktok加速器做跨境电商?可以加速Tiktok网络的节点分享
    TikTok是一款全球性的视频应用程序,越来越多的跨境电商企业开始在TikTok上开展业务。然而,由于地理位置和网络原因,许多跨境电商企业在使用TikTok时会遇到卡顿、延迟等问题,影响了业务的正常运营。 为了解决这些问题,许多跨境电商企业开始使用TikTok加速器。那么,新手如何使用TikTok......
  • 跨境出海蓬勃发展,茄子科技助力跨境电商实现品牌出海
    近两年随着全球消费者的需求愈发多元且细分,出海企业开始迈进品牌化方向。从工具、游戏到电商、社交,大厂们为突破国内增长瓶颈,纷纷进军海外市场,引起新一轮出海浪潮。然而出海并没有想象的那样容易,充满了风险与挑战。以跨境电商为例,除了吃透供应链红利的Shein等标志性企业,许多出海品......