我有以下 list :
dirtylist = ["lemons zested", "grated cheddar cheese", "carrots, thinly chopped"]
以下是我要从列表中的每个字符串项中删除的单词列表:
bannedWord = ['grated', 'zested', 'thinly', 'chopped', ',']
我try 生成的结果列表如下:
cleaner_list = ["lemons", "cheddar cheese", "carrots"]
到目前为止,我还无法做到这一点.我的try 如下:
import re
dirtylist = ["lemons zested", "grated cheddar cheese", "carrots, thinly chopped"]
cleaner_list = []
def RemoveBannedWords(ing):
pattern = re.compile("\\b(grated|zested|thinly|chopped)\\W", re.I)
return pattern.sub("", ing)
for ing in dirtylist:
cleaner_ing = RemoveBannedWords(ing)
cleaner_list.append(cleaner_ing)
print(cleaner_list)
这将返回:
['lemons zested', 'cheddar cheese', 'carrots, chopped']
我也try 过:
import re
dirtylist = ["lemons zested", "grated cheddar cheese", "carrots, thinly chopped"]
cleaner_list = []
bannedWord = ['grated', 'zested', 'thinly', 'chopped']
re_banned_words = re.compile(r"\b(" + "|".join(bannedWord) + ")\\W", re.I)
def remove_words(ing):
global re_banned_words
return re_banned_words.sub("", ing)
for ing in dirtylist:
cleaner_ing = remove_words(ing)
cleaner_list.append(cleaner_ing)
print(cleaner_list)
这将返回:
['lemons zested', 'cheddar cheese', 'carrots, chopped']
在这一点上,我有点迷茫,不确定我错在哪里.任何帮助都是非常感激的.