2017-06-29 107 views
0

我正在使用Microsoft Azure Face API,我只想获得眼镜响应。 继承人我的代码:我如何从Python中的这个列表中获取特定元素?

########### Python 3.6 ############# 
import http.client, urllib.request, urllib.parse, urllib.error, base64, requests, json 

############################################### 
#### Update or verify the following values. ### 
############################################### 

# Replace the subscription_key string value with your valid subscription key. 
subscription_key = '(MY SUBSCRIPTION KEY)' 

# Replace or verify the region. 
# 
# You must use the same region in your REST API call as you used to obtain your subscription keys. 
# For example, if you obtained your subscription keys from the westus region, replace 
# "westcentralus" in the URI below with "westus". 
# 
# NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using 
# a free trial subscription key, you should not need to change this region. 
uri_base = 'https://westcentralus.api.cognitive.microsoft.com' 

# Request headers. 
headers = { 
    'Content-Type': 'application/json', 
    'Ocp-Apim-Subscription-Key': subscription_key, 
} 

# Request parameters. 
params = { 
    'returnFaceAttributes': 'glasses', 
} 

# Body. The URL of a JPEG image to analyze. 
body = {'url': 'https://upload.wikimedia.org/wikipedia/commons/c/c3/RH_Louise_Lillian_Gish.jpg'} 

try: 
    # Execute the REST API call and get the response. 
    response = requests.request('POST', uri_base + '/face/v1.0/detect', json=body, data=None, headers= headers, params=params) 

    print ('Response:') 
    parsed = json.loads(response.text) 
    info = (json.dumps(parsed, sort_keys=True, indent=2)) 
    print(info) 

except Exception as e: 
    print('Error:') 
    print(e) 

,并返回像这样的列表:

[ 
    { 
    "faceAttributes": { 
     "glasses": "NoGlasses" 
    }, 
    "faceId": "0f0a985e-8998-4c01-93b6-8ef4bb565cf6", 
    "faceRectangle": { 
     "height": 162, 
     "left": 177, 
     "top": 131, 
     "width": 162 
    } 
    } 
] 

我只想眼镜属性,因此将只返回要么“眼镜”或“NoGlasses” 感谢您的任何提前帮助!

回答

1

我想你打印整个响应时,当你真的想深入并获取它的元素。试试这个:

print(info[0]["faceAttributes"]["glasses"]) 

我不知道该API是如何工作的,所以我不知道你指定的PARAMS实际上是做什么的,但这应该就这样结束了工作。

编辑:谢谢@Nuageux注意这确实是一个数组,你必须指定第一个对象是你想要的。

+1

你有没有检查?你错过了一个'[0]'。它应该是:'print(info [0] ['faceAttributes'] ['glasses'])' – Nuageux

0

我想,你可以得到在该列表中一些元素,所以你可以这样做:

info = [ 
    { 
    "faceAttributes": { 
     "glasses": "NoGlasses" 
    }, 
    "faceId": "0f0a985e-8998-4c01-93b6-8ef4bb565cf6", 
    "faceRectangle": { 
     "height": 162, 
     "left": 177, 
     "top": 131, 
     "width": 162 
    } 
    } 
] 

for item in info: 
    print (item["faceAttributes"]["glasses"]) 

>>> 'NoGlasses' 
0

你尝试:
glasses = parsed[0]['faceAttributes']['glasses']

+0

这工作谢谢你! – Carter4502

+0

不客气。 – MLenthousiast

+0

@ Carter4502如果您认为这是答案,您应该将其标记为答案 –

0

这看起来更像是一本字典比列表。字典是使用{key:value}语法定义的,可以通过它们的键的值来引用。在你的代码中,你有faceAttributes作为一个键值,该值包含另一个字典,其中键会导致你想要的最后一个值。

您的信息对象是一个包含一个元素的列表:一个字典。所以为了得到这个字典中的值,你需要告诉列表字典在哪里(在列表的头部,所以info [0])。

所以大家参考语法为:

#If you want to store it in a variable, like glass_var 
glass_var = info[0]["faceAttributes"]["glasses"] 
#Or if you want to print it directly 
print(info[0]["faceAttributes"]["glasses"]) 

这是怎么回事? info [0]是包含几个键的字典,包括faceAttributes,faceIdfaceRectanglefaceRectanglefaceAttributes都是字典本身与更多的键,你可以参考获得他们的价值。

您的打印树有显示你的字典里所有键和值,那么你可以参考使用正确的钥匙你的字典中的任何一部分:如果您在您的信息列表中的多个条目

print(info["faceId"]) #prints "0f0a985e-8998-4c01-93b6-8ef4bb565cf6" 
print(info["faceRectangle"]["left"]) #prints 177 
print(info["faceRectangle"]["width"]) #prints 162 

,那么你将有多个字典,你可以得到所有的输出像这样:

for entry in info: #Note: "entry" is just a variable name, 
        # this can be any name you want. Every 
        # iteration of entry is one of the 
        # dictionaries in info. 
    print(entry["faceAttributes"]["glasses"]) 

编辑:我没有看到这些信息是一本字典的名单,适应了这一事实。

相关问题