我正在尝试使用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)
关于python - 从停用词列表中重新划分多个字符串模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35660416/