1. 程式人生 > >requests 傳送post請求,呼叫百度API語言分析測試

requests 傳送post請求,呼叫百度API語言分析測試

import requests
import json
from BaiduSpider.settings import TOKEN

class Emotion(object):
    """
            "sentiment":2,    //表示情感極性分類結果
            "confidence":0.40, //表示分類的置信度
            "positive_prob":0.73, //表示屬於積極類別的概率
            "negative_prob":0.27  //表示屬於消極類別的概率
    """
    def __init__(self):
        self.url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token={}'
        self.header = {'Content-Type':'application/json'}
    @classmethod
    def post(cls,text):
        body = {
            'text':text
        }
        res = requests.post(cls().url.format(TOKEN),json=body,headers=cls().header)
        # res = requests.post(cls().url.format(TOKEN),data=json.dumps(body),headers=cls().header)
        res = json.loads(res.text)
        print(type(res))
        positive_prob,negative_prob =res['items'][0]['positive_prob'],res['items'][0]['negative_prob']
        return positive_prob,negative_prob

if __name__ == '__main__':
    text = 'jeep自由光真實油耗'

    res = Emotion.post(text)