2017-06-29 113 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"]) 

編輯:我沒有看到這些信息是一本字典的名單,適應了這一事實。

相關問題