2017-06-04 59 views
0

在調用情感API後,我得到以下響應。我怎樣纔能有一個只獲得幸福分數的變量?我想要一些像data = happiness的東西,那麼我可以打印數據。Microsoft-Cognitive:Emotion API

{ 
    "FaceRectangle": { 
     "Top": 141, 
     "Left": 331, 
     "Width": 52, 
     "Height": 52 
    }, 
    "Scores": { 
     "Anger": 0.002451766, 
     "Contempt": 0.0005512201, 
     "Disgust": 0.0063303886, 
     "Fear": 0.000122375583, 
     "Happiness": 0.9589189, 
     "Neutral": 0.0222537462, 
     "Sadness": 0.008983561, 
     "Surprise": 0.000388026354 
    } 
} 

這裏是Python代碼

import http.client, urllib.request, urllib.parse, urllib.error, base64, sys 

headers = { 
    # Request headers. Replace the placeholder key below with your subscription key. 
    'Content-Type': 'application/octet-stream', 
    'Ocp-Apim-Subscription-Key': '**************************', 
} 

params = urllib.parse.urlencode({ 


     }) 

body = open('clouds.jpg','rb').read() 

try: 
    conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com') 
    conn.request("POST", "/emotion/v1.0/recognize?%s" % params, body, headers) 

    response = conn.getresponse() 
    data = response.read() 
    print(data) 

    conn.close() 

除例外爲e: 打印(e.args)

+2

'數據[「成績」] [「幸福」]'(假設你將結果保存在一個名爲'變量數據) – falsetru

+0

我想要的東西像數據=幸福然後我可以只能打印數據 –

回答

0

@falsetru是正確的,但你要注意,情緒API

  • 返回一個面陣列,即使只有一個,並且
  • 的字段名稱將是駱駝套管,不像片斷您添加
import requests 

body = {'url':'YOUR-IMAGE-URL'} 
headers = { 
    'Content-Type': 'application/json', 
    'Ocp-Apim-Subscription-Key': 'YOUR-KEY' 
} 
req = requests.post('https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize', headers=headers, data=str(body)) 
faces = req.json() 
for face in faces: 
    print face['scores']['happiness'] 
+0

我想要的東西像數據=幸福,然後我可以只能打印數據 –

+0

我仍然得到這個錯誤:TypeError:字符串索引必須是整數 –

+0

你調用API的端點是什麼?錯誤描述聽起來像你得到了不同的結果比我期待的。 如果你有一個面陣列,並且想獲得一組幸福分數,你可以做一些像'map(lambda f:f ['scores'] ['happiness'],faces)' – cthrash