python - 无法弄清楚如何使用 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
解决方案
这里有几点需要注意:
- 您有一个 for 循环,每次迭代都访问第一个条目 (
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
推荐阅读
- selenium - 硒中的引导下拉处理
- pandas - 拆分和重组熊猫数据框中的列表
- ibm-midrange - 即使签名 ID 从程序对象到服务程序不同,程序也不会引发签名冲突错误
- sql - Cognos Analytics:关于 CASE WHEN 表达式的 QE-DEF-0459
- neo4j - 在一台机器上运行两个 Neo4j 实例作为 Windows 服务
- php - laravel - 未找到自定义类
- tcl - 如何存储按钮按下的值?
- php - 在方法中使准备好的语句静态
- java - 使用bufferimage java swing绘制多个形状
- haskell - 仍然混淆带有多个箭头的类型签名如何工作