背景我的結構如下:trash = [ {'href': 'https://www.simplyrecipes.com/recipes/cuisine/portuguese/'}, {'href': 'https://www.simplyrecipes.com/recipes/cuisine/german/'}, {'href': 'https://www.simplyrecipes.com/recipes/season/seasonal_favorites_spring/'}, {'href': 'https://www.simplyrecipes.com/recipes/type/condiment/'}, {'href': 'https://www.simplyrecipes.com/recipes/ingredient/adobado/'}] {'href': 'https://www.simplyrecipes.com/', 'title': 'Simply Recipes Food and Cooking Blog', 'rel': ['home']},]如您所見,大多數鍵是'href',大多數值包含'https://www.simplyrecipes.com/recipes/'. 問題是那些不符合此命名約定的鍵和值......代碼:此代碼遍歷結構并使用re.findall獲取之間的字符串值'recipes/',然后繼續/為其對應的值創建一個新的鍵名。for x in trash: for y in x.values(): txt = '' for i in re.findall("recipes/.*", y): txt += i title = txt.split('/')[1] print({title: y})輸出:假設我刪除了不符合被命名和包含代碼字符串值的命名約定的keys和,如下所示:values'href''https://www.simplyrecipes.com/recipes/'{'cuisine': 'https://www.simplyrecipes.com/recipes/cuisine/portuguese/'}{'cuisine': 'https://www.simplyrecipes.com/recipes/cuisine/german/'}{'season': 'https://www.simplyrecipes.com/recipes/season/seasonal_favorites_spring/'}{'type': 'https://www.simplyrecipes.com/recipes/type/condiment/'}{'ingredient': 'https://www.simplyrecipes.com/recipes/ingredient/adobado/'}問題:代碼的問題是,TypeError: expected string or bytes-like object如果結構的鍵和值不符合代碼中的命名約定,我會得到一個。問題:我將如何改進這段代碼,以便它跳過任何未命名的鍵'href',如果它們被命名'href',如果它們的值不包含,將跳過'https://www.simplyrecipes.com/recipes/'?
1 回答

森林海
TA貢獻2011條經驗 獲得超2個贊
for d in trash:
for key, value in d.items():
if key != "href" or "https://www.simplyrecipes.com/recipes/" not in value:
continue # Move onto next iteration
txt = ''
for i in re.findall("recipes/.*", value):
txt += i
title = txt.split('/')[1]
print({title: value})
您可以使用 迭代字典的鍵和值dict.items()。然后你可以使用if語句來檢查你的條件,continue如果他們不滿足。
添加回答
舉報
0/150
提交
取消