gpt4 book ai didi

python - 如何从特定字典键的值列表中删除单词?

转载 作者:行者123 更新时间:2023-12-01 00:56:01 25 4
gpt4 key购买 nike

我需要从字典列表中特定键的值中删除单词列表。

以下是我的数据的示例:

words = ['cloves', 'packed']

data = [{'title': 'Simple Enchiladas Verdes',
'prep_time': '15 min',
'cook_time': '30 min',
'ingredients': ['chicken breast', 'tomato sauce', 'garlic cloves', 'fresh packed cilantro']
'instructions': ['some text...'],
'category': 'dessert',
'cuisine': 'thai',
'article': ['some text...']
},
{...}, {...}]

期望的输出:

data = [{'title': 'Simple Enchiladas Verdes',
'prep_time': '15 min',
'cook_time': '30 min',
'ingredients': ['chicken breast', 'tomato sauce', 'garlic', 'fresh cilantro']
},
{...}, {...}]

我尝试过不同的代码:

remove = '|'.join(words)
regex = re.compile(r'\b('+remove+r')\b', flags=re.IGNORECASE)

for dct in data:
dct['ingredients']= list(filter(lambda x: regex.sub('', x), dct['ingredients']))

但这会返回以下错误:TypeError: sub() 缺少 1 个必需的位置参数:'string'

我尝试过的其他代码:

for dct in data:
dct['ingredients']= list(filter(lambda x: x != words, dct['ingredients']))
for dct in data:
dct['ingredients']=[[el for el in string if el in words ] for string in dct['ingredients']]
for dct in data:
for string in dct['ingredients']:
dct['ingredients'] = list(filter(lambda x: x not in words, dct['ingredients']))

但他们都没有解决我的问题。

最佳答案

为什么不使用 list 理解与 dictionary 理解:

data = [{k:([' '.join([s for s in x.split() if s not in words]) for x in v] if k == 'ingredients' else v) for k, v in i.items()} for i in data]

关于python - 如何从特定字典键的值列表中删除单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56252703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com