背景我的結(jié)構(gòu)如下: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']},]如您所見,大多數(shù)鍵是'href',大多數(shù)值包含'https://www.simplyrecipes.com/recipes/'. 問題是那些不符合此命名約定的鍵和值......代碼:此代碼遍歷結(jié)構(gòu)并使用re.findall獲取之間的字符串值'recipes/',然后繼續(xù)/為其對應(yīng)的值創(chuàng)建一個(gè)新的鍵名。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})輸出:假設(shè)我刪除了不符合被命名和包含代碼字符串值的命名約定的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如果結(jié)構(gòu)的鍵和值不符合代碼中的命名約定,我會得到一個(gè)。問題:我將如何改進(jìn)這段代碼,以便它跳過任何未命名的鍵'href',如果它們被命名'href',如果它們的值不包含,將跳過'https://www.simplyrecipes.com/recipes/'?
1 回答

森林海
TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
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如果他們不滿足。
添加回答
舉報(bào)
0/150
提交
取消