【NLP】情感识别,积极、消极、中性(一)

此代码只做感情识别,在(二)将结合语音识别

import requests
import json


# 情感分析
def sentiment_classify(access_token, text):
    url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token={}".format(access_token)
    if len(text.encode())<2048: # 情感分析输入上限是2048个字节,小于2048直接调用
        data = {"text": text}
        data = json.dumps(data)
        response = requests.post(url, data=data)
        res = response.text.find("items") # items在返回值中判断结果是否正确返回

        if (res != -1): # 如果结果不等于-1,则正确返回
            json_data = json.loads(response.text)
            sentiment = json_data["items"][0]["sentiment"] # 判断感情类别(0:负向,1:中性,2:正向)
            positive_prob = json_data["items"][0]["positive_prob"] # 返回积极的概率
            negative_prob = json_data["items"][0]["negative_prob"] # 返回消极的概率
            if sentiment == 2:
                print("......情感为积极......, 可信度为 {}".format(positive_prob))
            elif sentiment == 0:
                print("......情感为消极......, 可信度为 {}".format(negative_prob))
            else:
                print("......情感为中性......")
        else:
            print("抱歉,遇见未知错误")

    return sentiment


# 获取access_token
def get_access_token(apikey, secretkey):

    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}".format(apikey, secretkey)
    response = requests.get(url)
    return response


if __name__ == "__main__":
    sentiment_api = "********" # 情感识别AK
    sentiment_secret = "*********" # 情感识别SK
    res = get_access_token(sentiment_api, sentiment_secret)
    access_token = res.json()["access_token"] # 获取access_token
    text = "好难过"    # 测试的句子
    sentiment_res = sentiment_classify(access_token, text)
    print(sentiment_res)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值