我想從包含關於歌曲的元數據的JSON對象中提取幾個元素,使用Python。爲了測試信息是否可用,我爲每個元數據元素使用try語句。另外,對於稍後在我的程序中需要做的一些字符串處理,我將每個值保存在一個不同的變量中。如何提高在Python中重複使用try語句?
有關如何改進以下代碼以便爲每個不同的元數據值創建try/except語句的任何建議?
if len(r['response']['songs']) is not 0:
# Request information about the artist
artist_desc_string = "http://developer.echonest.com/api/v4/artist/terms?api_key="+api_key+\
"&name="+artist+"&format=json"
r2 = requests.get(artist_desc_string).json()
# Extract information from the song JSON
try:
title = r['response']['songs'][0]['title']
except (IndexError, KeyError):
title = "NULL"
try:
artist_name = r['response']['songs'][0]['artist_name']
except (IndexError, KeyError):
artist_name = "NULL"
try:
artist_location = r['response']['songs'][0]['artist_location']['location'].replace(',','*')
except (IndexError, KeyError):
artist_location = "NULL"
try:
...
...
這個問題似乎是題外話,因爲它屬於上http://codereview.stackexchange.com – jonrsharpe
如果你只是希望在處理KeyError異常最後一個元素,你可以看看'dict.get',但是因爲你正沿着查找路徑的整個長度捕捉任何東西,所以不是真的。你也許可以把路徑放在一個列表中,並循環它們,但這只是可以更簡潔,可能更慢。 –
只是一個觀察:你總是可以將'r ['response'] ['songs'] [0]'賦值給一個變量,看看它是如何反覆使用的。 – Manhattan