【问题标题】:Microsoft-Cognitive : Emotion API微软认知:情感 API
【发布时间】:2017-10-04 15:46:38
【问题描述】:

我在调用情感 api 后得到以下响应。我怎样才能拥有一个只获得幸福分数的变量?我想要像 data=happiness 这样的东西,然后我就可以打印数据了。

{
    "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)

【问题讨论】:

  • data['Scores']['Happiness'](假设您将结果保存在名为data的变量中)
  • 我想要像 data=happiness 这样的东西,然后我就可以打印数据了

标签: python-3.x api microsoft-cognitive


【解决方案1】:

@falsetru 是正确的,但你应该注意 Emotion API

  • 返回一组人脸,即使只有一个人脸,并且
  • 字段名称将采用驼峰式大小写,与您添加的 sn-p 不同
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']

【讨论】:

  • 我想要像 data=happiness 这样的东西,然后我就可以打印数据了
  • 我仍然得到这个错误:TypeError: string indices must be integers
  • 您在调用 API 的哪个端点?错误描述听起来你得到的结果与我预期的完全不同。如果你有一组面孔,并且想要获得一组幸福分数,你会做类似map(lambda f: f['scores']['happiness'], faces)
  • 检查上面的python代码我刚刚编辑了问题然后告诉我如何创建一个变量来保存幸福分数
  • import json faces = json.loads(data) happiness = faces[0]['scores']['happiness'] if len(faces)>0 else 0
猜你喜欢
  • 2017-12-24
  • 2017-10-21
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2017-05-25
  • 1970-01-01
  • 2017-09-25
相关资源
最近更新 更多