Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从停止字列表中重新生成多个字符串模式_Python_Regex - Fatal编程技术网

Python 从停止字列表中重新生成多个字符串模式

Python 从停止字列表中重新生成多个字符串模式,python,regex,Python,Regex,我正试图使用re.sub将停止字列表替换为空格,但对于如何准确地使用for循环来实现这一点,我感到很困惑。我下面的示例代码是尝试将i插入regexp模式,其中i是for循环中的每个停止字,但我返回了我输入的相同文本 text = codecs.open(path.join(d, 'replyAllText.txt'),'r', 'utf-8').read() text = text.lower() test = ['to', 'all', 'the'] for i in test: te

我正试图使用
re.sub
将停止字列表替换为空格,但对于如何准确地使用for循环来实现这一点,我感到很困惑。我下面的示例代码是尝试将
i
插入regexp模式,其中
i
是for循环中的每个停止字,但我返回了我输入的相同文本

text = codecs.open(path.join(d, 'replyAllText.txt'),'r', 'utf-8').read()
text = text.lower()



test = ['to', 'all', 'the']

for i in test:
text = re.sub('\b{}\b'.format(i) ," ", text)

print(text)

正如@tdelaney所说,缺少
r
前缀是导致您出现问题的原因。但是你也有更好的方法来完成你的任务。不必重复调用
re.sub
,您可以使用交替操作
|
构建更好的正则表达式,并且只调用
re.sub
一次:

test = ['to', 'all', 'the']
master_regex = '|'.join(r'\b{}\b'.format(w) for w in test)
text = re.sub(master_regex, ' ', text)

您需要转义
\b
或使用原始字符串,如
r'\b{}\b'
re。对于这种情况,sub
算法效率低下,尤其是对于大型列表/文本。我将从文件中构建前缀树,并在文本本身上循环。