首页 > 解决方案 > 无法弄清楚如何使用 re.sub 并遍历列表

问题描述

我希望它遍历列表并检查列表中的每个项目是否在 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 

标签: python

解决方案


这里有几点需要注意:

  1. 您有一个 for 循环,每次迭代都访问第一个条目 ( wordList[0]) 而不是当前条目 ( word)。
  2. 您每次迭代都会覆盖您的输出,因此只会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

推荐阅读