2017-06-05 58 views
-1

在調用情感API後,我得到以下響應。Microsoft-Cognitive:Python中的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 = { 
    key. 
    'Content-Type': 'application/octet-stream', 
    'Ocp-Apim-Subscription-Key': '************************', 
} 

params = urllib.parse.urlencode({ 


    }) 
body = open('my_image.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() 
except Exception as e: 
    print(e.args) 

回答

0

我認爲這應該工作:

import json 
dump = json.dumps(data) 
json_string = json.loads(dump) 
happiness = str(json_string[0]['Scores']['Happiness']) 
+0

我得到這個錯誤>> 「 '廉政' 對象不是標化」 –

+0

嘗試上述 – joshi123

+0

編輯響應'數據「已經是一個字符串。所以你應該跳過'json.dumps'調用,只做一個'json.loads'。看起來如果你想要一個數值,也可以跳過'str'調用。 – cthrash

-1
import ast 

data = response.read() 
b = data.decode("utf-8") #bytes to string conversion 
c = ast.literal_eval(b) #string to list conversion 
print(c[0]['scores']['happiness']) #parsing 
相關問題