调用百度AI开放平台的接口,进行情感分析

305 阅读1分钟

【NLP】百度AI开放平台自然语言处理API调用(情感分析案例)

     import urllib.request
     import json
     
     APIKey = "xxx"
     SecretKey = "xxx"

     def get_access_token():
         """
         通过API KeySecret Key这2个参数,获取百度AI平台的Access Token
         """
         host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(APIKey,SecretKey)
         request = urllib.request.Request(host)
         request.add_header('Content-Type', 'application/json; charset=UTF-8')
         response = urllib.request.urlopen(request)
         content = response.read().decode('utf-8')
         rdata = json.loads(content)
         access_token = rdata['access_token']
         
         return access_token
         
     def sentiment_classify(text,access_token):
         """
         获取文本的感情偏向(消极 or 积极 or 中立)
         参数:
         text:str 本文
         """
         raw = {"text":"内容"}
         raw['text'] = text
         data = json.dumps(raw).encode('utf-8')
         host = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token="+access_token
         request = urllib.request.Request(url=host,data=data)
         request.add_header('Content-Type', 'application/json')
         response = urllib.request.urlopen(request)
         content = response.read().decode('utf-8')
         rdata = json.loads(content)
         
         return rdata
         
     返回的值为:
         {'log_id': 5377788657827174316,
         'text': '苹果是一家伟大的公司',
         'items': [{'positive_prob': 0.727802,
           'confidence': 0.395115,
           'negative_prob': 0.272198,
           'sentiment': 2}]}