gpt4 book ai didi

python re.sub 带有要查找的单词列表

转载 作者:太空狗 更新时间:2023-10-30 01:59:50 26 4
gpt4 key购买 nike

我不太熟悉 RE 但我正在尝试遍历列表并使用 re.sub从变量 first_word 中保存的大文本 block 中取出多个项目.

我使用 re.sub首先删除标签,这工作正常,但我接下来想删除 exclusionList 中的所有字符串变量,我不确定该怎么做。

感谢您的帮助,这是引发异常的代码。

exclusionList = ['+','of','<ET>f.','to','the','<L>L.</L>']

for a in range(0, len(exclusionList)):
first_word = re.sub(exclusionList[a], '',first_word)

异常(exception)情况:

first_word = re.sub(exclusionList[a], '',first_word)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 245, in _compile
raise error, v # invalid expression error: nothing to repeat

最佳答案

加号是正则表达式中的一个运算符,意思是“前面的一个或多个重复”。例如,x+ 表示 x 的一次或多次重复。如果你想找到并替换实际的 + 符号,你需要像这样转义它:re.sub('\+', '', string)。因此,更改排除列表中的第一个条目。

你也可以消除 for 循环,像这样:

exclusions = '|'.join(exclusionList)
first_word = re.sub(exclusions, '', first_word)

管道符号 | 表示正则表达式中的析取,因此 x|y|z 匹配 x 或 y 或 z。

关于python re.sub 带有要查找的单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10968558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com