我希望它迭代列表并检查列表中的每个项目是否都在var txt中,如果它们在那里,则用空格替换它们。如您所见,我只能获取列表中的第一个要替换的项目。如何让它迭代列表中的每个项目?感谢。
import re
txt='affirmed and the affirmance and AFFIRMED and Affirm case'
wordList = ['case', 'affirm\w+', '(ca\w+)']
for word in wordList:
out = re.sub(wordList[0], '', txt, re.I)
#out = re.sub(r'\Abaffirm.+', '', txt, re.IGNORECASE)
print txt
print out
输出:
affirmed and the affirmance and AFFIRMED and Affirm case
affirmed and the affirmance and AFFIRMED and Affirm
答案 0 :(得分:0)
这里需要注意几点:
wordList[0]
)而不是当前条目(word
)。wordList
中的最后一个条目。因此,工作循环可能如下所示:
wordList = ['case', 'affirm\w+', '(ca\w+)']
out = txt
for word in wordList:
out = re.sub(word, '', out, re.I)
print txt
print out
在你的建议发挥作用之后,我对它进行了进一步的编辑,缩短了它。
import re
txt='affirmed and the affirmance and AFFIRMED and Affirm case'
wordList = ['affirm\w+', '(ca\w+)']
for word in wordList:
txt = re.sub(word, '', txt, re.I)
print txt