【NLP】百度AI平臺自然語言處理API呼叫(情感分析案例)
阿新 • • 發佈:2019-02-16
首先先註冊登入百度AI平臺,自然語言處理是免費的,有5 QPS,夠用了,不夠用可以申請增加。
我申請增加至10 QPS,通過得很快。
相關配置準備
找到百度AI平臺的NLP入口:
看到自然語言處理
點選進入
進入之後跳轉到自然語言處理產品頁
點選建立應用,應用建立後會有AppID、API Key、Secret Key這些引數。後續使用會利用到這些引數!
使用百度NLP的API需要獲取Access Token,這個token有效期一個月。
獲取Access Token需要使用之前得到的引數API Key和Secret Key。
但是沒有Python3的,以下程式碼是Python3獲取Access Token。
def get_access_token(): """ 獲取百度AI平臺的Access Token """ host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]' 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) return rdata['access_token']
返回Access Token字串。
開始使用
開始使用需要的NLP API,我這裡使用情感分析API。需要修改Access Token!
def sentiment_classify(text): """ 獲取文字的感情偏向(消極 or 積極 or 中立) 引數: text:str 本文 """ raw = {"text":"內容"} raw['text'] = text data = json.dumps(raw).encode('utf-8') AT = "Access Token" host = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token="+AT 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}]}
解析:
引數 | 說明 | 描述 |
---|---|---|
log_id | uint64 | 請求唯一標識碼 |
sentiment | int | 表示情感極性分類結果,0:負向,1:中性,2:正向 |
confidence | float | 表示分類的置信度,取值範圍[0,1] |
positive_prob | float | 表示屬於積極類別的概率 ,取值範圍[0,1] |
negative_prob | float | 表示屬於消極類別的概率,取值範圍[0,1] |
例項:
完成
結論
百度的NLP API還是挺好用的,但是不要太依賴於百度AI,這東西估計後期會收錢的,在NLP結合的產品探索階段可以使用百度的NLP API 中期就需要自己研發了,自己的技術才是可靠的。
不依賴於他人,堅持研發,才是科技企業發展之道。