gpt4 book ai didi

python - 从停用词列表中重新替换多个字符串模式

转载 作者:行者123 更新时间:2023-11-30 22:59:38 25 4
gpt4 key购买 nike

我正在尝试使用 re.sub 将停用词列表替换为空格,但对如何使用 for 循环来完成此操作感到困惑。下面的示例代码尝试将 i 插入到正则表达式模式中,其中 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/

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