from aip import AipNlp
from openpyxl import load_workbook
import time

# 填写你的自然语言处理应用的App ID、API Key、Secret Key
APP_ID = ''
API_Key = ''
Secret_Key = ''
client = AipNlp(APP_ID, API_Key, Secret_Key)
wb = load_workbook('./data/商品评价.xlsx')
ws = wb.active
posCount, negCount, neuCount = 0, 0, 0
# 遍历全部商品评价
for row in range(2, ws.max_row + 1):
    comment = ws.cell(row=row, column=4).value
    # 调用评论观点抽取接口
    options = {'type': 11}
    result = client.commentTag(comment, options)
    time.sleep(0.5)
    # 输出观点抽取接口返回值的关键信息
    print('第%d条商品评价的观点抽取：' % (row - 1))
    print('-----------------------------------')
    if len(result['items']) == 0:
        print('该评论观点与本商品无关')
        neuCount += 1
    else:
        for item in result['items']:
            if item['sentiment'] == 1:
                print('观点中性，中性的词语为：', item['prop'], item['adj'])
                neuCount += 1
            elif item['sentiment'] == 2:
                print('观点中性，中性的词语为：', item['prop'], item['adj'])
                posCount += 1
            else:
                print('观点消极，消极的词语为：', item['prop'], item['adj'])
                negCount += 1
# 输出观点抽取的统计结果
allCount = negCount + neuCount + posCount
print('\n观点总数为:', allCount)
print('积极观点数：', posCount, '所占比例：', round(posCount / allCount * 100, 4), '%')
print('中性观点数：', neuCount, '所占比例：', round(neuCount / allCount * 100, 4), '%')
print('消极观点数：', negCount, '所占比例：', round(negCount / allCount * 100, 4), '%')
