我打电话给情感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 :(得分:0)
我认为这应该有效:
import json
dump = json.dumps(data)
json_string = json.loads(dump)
happiness = str(json_string[0]['Scores']['Happiness'])
答案 1 :(得分:-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