我对RE不太熟悉,但我试图迭代一个列表并用来re.sub
从变量中保存的大块文本中取出多个项目first_word
.
我首先使用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)
Run Code Online (Sandbox Code Playgroud)
例外情况:
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
Run Code Online (Sandbox Code Playgroud)
加号是正则表达式中的运算符,意思是"前面的一个或多个重复".例如,x+
意味着一次或多次重复x
.如果你想找到并替换实际的+
标志,你需要像这样逃避:re.sub('\+', '', string)
.因此,请更改exclusionList中的第一个条目.
您也可以消除for循环,如下所示:
exclusions = '|'.join(exclusionList)
first_word = re.sub(exclusions, '', first_word)
Run Code Online (Sandbox Code Playgroud)
管道符号|
表示正则表达式中的析取,因此x|y|z
匹配x或y或z.