我有一个列表,如下所示:
exclude = ["please", "hi", "team"]
我有一个字符串如下:
text = "Hi team, please help me out."
我希望我的字符串看起来像:
text = ", help me out."
有效地去除列表中可能出现的所有单词 exclude
我尝试了以下方法:
if any(e in text.lower()) for e in exclude:
print text.lower().strip(e)
但是上面的if
语句返回一个布尔值,因此我得到以下错误:
NameError: name 'e' is not defined
我该如何完成?
像这样吗?
>>> from string import punctuation
>>> ' '.join(x for x in (word.strip(punctuation) for word in text.split())
if x.lower() not in exclude)
'help me out
如果您要保留结尾/前导标点中不存在的单词exclude
:
>>> ' '.join(word for word in text.split()
if word.strip(punctuation).lower() not in exclude)
'help me out.'
第一个等效于:
>>> out = []
>>> for word in text.split():
word = word.strip(punctuation)
if word.lower() not in exclude:
out.append(word)
>>> ' '.join(out)
'help me out'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句