我想我会在这里使用正则表达式:
import re
a=["Britney spears", "red dog", "\xa2xe3"]
regex = re.compile('|'.join(re.escape(x) for x in a))
b=["cat","dog","red dog is stupid", "good stuff \xa2xe3", "awesome Britney spears"]
b = [regex.sub("",x) for x in b ]
print (b) #['cat', 'dog', ' is stupid', 'good stuff ', 'awesome ']
这样,正则表达式引擎可以优化替代列表的测试。
这里有一堆替代方法来展示不同的正则表达式的行为方式。
import re
a = ["Britney spears", "red dog", "\xa2xe3"]
b = ["cat","dog",
"red dog is stupid",
"good stuff \xa2xe3",
"awesome Britney spears",
"transferred dogcatcher"]
#This version leaves whitespace and will match between words.
regex = re.compile('|'.join(re.escape(x) for x in a))
c = [regex.sub("",x) for x in b ]
print (c) #['cat', 'dog', ' is stupid', 'good stuff ', 'awesome ', 'transfercatcher']
#This version strips whitespace from either end
# of the returned string
regex = re.compile('|'.join(r'\s*{}\s*'.format(re.escape(x)) for x in a))
c = [regex.sub("",x) for x in b ]
print (c) #['cat', 'dog', 'is stupid', 'good stuff', 'awesome', 'transfercatcher']
#This version will only match at word boundaries,
# but you lose the match with \xa2xe3 since it isn't a word
regex = re.compile('|'.join(r'\s*\b{}\b\s*'.format(re.escape(x)) for x in a))
c = [regex.sub("",x) for x in b ]
print (c) #['cat', 'dog', 'is stupid', 'good stuff \xa2xe3', 'awesome', 'transferred dogcatcher']
#This version finally seems to get it right. It matches whitespace (or the start
# of the string) and then the "word" and then more whitespace (or the end of the
# string). It then replaces that match with nothing -- i.e. it removes the match
# from the string.
regex = re.compile('|'.join(r'(?:\s+|^)'+re.escape(x)+r'(?:\s+|$)' for x in a))
c = [regex.sub("",x) for x in b ]
print (c) #['cat', 'dog', 'is stupid', 'good stuff', 'awesome', 'transferred dogcatcher']