I have the following list:
dirtylist = ["lemons zested", "grated cheddar cheese", "carrots, thinly chopped"]
This is a list of words that I want to remove from each of the string items in the list:
bannedWord = ['grated', 'zested', 'thinly', 'chopped', ',']
The resulting list that I am trying to generate is this:
cleaner_list = ["lemons", "cheddar cheese", "carrots"]
So far, I have been unable to achieve this. My attempt is as follows:
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)
This returns:
['lemons zested', 'cheddar cheese', 'carrots, chopped']
I have also tried:
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)
This returns:
['lemons zested', 'cheddar cheese', 'carrots, chopped']
I'm a bit lost at this point and not sure where I'm going wrong. Any help is much appreciated.