此代码只做感情识别,在(二)将结合语音识别
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)