当前位置:   article > 正文

基于百度AI接口的商品评论情感倾向性分析

基于百度AI接口的商品评论情感倾向性分析

开篇说明

阅读本篇文章前建议先将百度AI接口应用创建好,调试清楚,该流程在另一篇文章中介绍

百度AI接口应用创建与调试流程-CSDN博客

项目介绍

本项目接入两个百度AI接口(情感倾向性分析与机器翻译)对商品评论进行分析,得到结果后抽出置信度与积极消极概率再根据公式判断情感极性

项目架构

架构抽象为接口封装,只需要再Analysis.py中修改相关参数即可实现分析

规定Excel文档名称格式为:

sheet_name = "AmazonInfo_" + country + "_" + kind + ".xlsx"

项目代码

包括数据集一同打包在百度网盘,在pycharm中创建好新项目导入即可

链接:https://pan.baidu.com/s/1j4fvWpNUx1rse0VyDwAxNg?pwd=q7k7 
提取码:q7k7

文字介绍如下

Analysis.py

  1. import json
  2. import ApiConnect
  3. import GetData
  4. import Judge_confidence
  5. # 定义分析哪一个Excel数据
  6. # en_从英文翻译为中文,fr_从法语翻译为中文等等
  7. lan_code = "en"
  8. # 分析不同国家的亚马逊平台
  9. country = "us"
  10. # 分析亚马逊平台的商品
  11. kind = "furniture"
  12. # 数据总量
  13. row_length = GetData.text(1, country, lan_code, kind)[1]
  14. # 记录情感极性数量
  15. mid_num = 0
  16. neg_num = 0
  17. pos_num = 0
  18. for i in range(2, row_length):
  19. # 将判断数据转化为字典后获取其中包含了情感极性与置信度数据的items
  20. items = json.loads(ApiConnect.method(i, country, lan_code, kind)).get("items")
  21. # print(GetData.text(i, "us", "en", "furniture")[0])
  22. # print(items)
  23. # 获取情感极性几率与置信度
  24. conf = items[0].get("confidence")
  25. neg = items[0].get("negative_prob")
  26. pos = items[0].get("positive_prob")
  27. # 根据数据判断情感极性
  28. sentiment = Judge_confidence.determine_sentiment(conf, neg, pos)
  29. # print(sentiment)
  30. if sentiment == "积极":
  31. pos_num += 1
  32. elif sentiment == "消极":
  33. neg_num += 1
  34. else:
  35. mid_num += 1
  36. print("pos_num:", pos_num, "neg_num:", neg_num, "mid_num:", mid_num)

ApiConnect.py

这个代码应从百度AI接口的API文档中直接复制后再修改逻辑,由于我更改了他的方法调用参数,所以放出来以供参考

  1. import requests
  2. import json
  3. import GetData
  4. API_KEY = ""
  5. SECRET_KEY = ""
  6. def method(num_method, country, lan_code, kind):
  7. url = ("https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=KuQwQKes8e2eM8EwmTiqCyMYO6yxSiWO"
  8. "&access_token=") + get_access_token()
  9. text = GetData.text(num_method, country, lan_code, kind)[0]
  10. payload = json.dumps(text)
  11. headers = {
  12. 'Content-Type': 'application/json',
  13. 'Accept': 'application/json'
  14. }
  15. response = requests.request("POST", url, headers=headers, data=payload)
  16. return response.text
  17. def get_access_token():
  18. """
  19. 使用 AK,SK 生成鉴权签名(Access Token)
  20. :return: access_token,或是None(如果错误)
  21. """
  22. url = "https://aip.baidubce.com/oauth/2.0/token"
  23. params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
  24. return str(requests.post(url, params=params).json().get("access_token"))

GetData.py

  1. import json
  2. import openpyxl
  3. import LanTrans
  4. # num_text 由Analysis定义,从第二行数据自动开始
  5. def text(num_text, country, lan_code, kind):
  6. sheet_name = "AmazonInfo_" + country + "_" + kind + ".xlsx"
  7. wb = openpyxl.load_workbook(sheet_name)
  8. # 表名注意大小写
  9. sheet = wb["Sheet1"]
  10. row = sheet.max_row
  11. # 此处需要修改column,按照自己的excel文档确认,我这里是第六列
  12. cell_value = LanTrans.trans(sheet.cell(row=num_text, column=6).value, lan_code)
  13. cell_value_json = json.loads(cell_value)
  14. case_dict = {"text": cell_value_json["result"]["trans_result"][0]["dst"]}
  15. return case_dict, row

Judge_confidence.py

  1. def determine_sentiment(confidence, negative_prob, positive_prob):
  2. if confidence > 0.7:
  3. if positive_prob > negative_prob:
  4. return "积极"
  5. else:
  6. return "消极"
  7. elif 0.4 < confidence <= 0.7:
  8. if positive_prob > 0.6:
  9. return "积极"
  10. elif negative_prob > 0.6:
  11. return "消极"
  12. else:
  13. return "中立/不明显"
  14. else:
  15. return "中立/不明显"

LanTrans.py

该接口代码修改逻辑与前面相同

  1. import requests
  2. import json
  3. API_KEY = ""
  4. SECRET_KEY = ""
  5. def trans(value, lan_code):
  6. url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + get_access_token()
  7. q = {"from": lan_code,
  8. "to": "zh",
  9. "q": value
  10. }
  11. payload = json.dumps(q)
  12. headers = {
  13. 'Content-Type': 'application/json',
  14. 'Accept': 'application/json'
  15. }
  16. response = requests.request("POST", url, headers=headers, data=payload)
  17. return response.text
  18. def get_access_token():
  19. """
  20. 使用 AK,SK 生成鉴权签名(Access Token)
  21. :return: access_token,或是None(如果错误)
  22. """
  23. url = "https://aip.baidubce.com/oauth/2.0/token"
  24. params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
  25. return str(requests.post(url, params=params).json().get("access_token"))

项目维护

预计更新:

输出情感极性判断结果到Excel中,含confidence,positive_prob,negative_prob,emo_result

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/521584
推荐阅读
相关标签
  

闽ICP备14008679号