我有一个如下所示的列表:
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
语句返回一个 bool 值,因此我得到以下错误:
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'
关于Python如何根据列表中的项目从字符串中剥离字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27057101/