首页 > 解决方案 > 在 Python 中使用 re.sub 时如何排除单词?

问题描述

我有相当多的所有格,我正在尝试相应地清理它们。

我想在删除它们时排除一两个词。到目前为止,这是我不工作的例子:

import re
re.sub(r"(s')", '', "united states' and washingtons' and civilians' and qur'an")

在上述情况下,我希望“状态”不要被切掉。感谢您的时间和帮助!

标签: pythonregex

解决方案


您可以在后面使用否定的外观,告诉正则表达式只对后面'(?<!something)' 没有的单词进行切片:'state'"s'"

import re
print(re.sub(r"(?<! state)s'", '', "united states' and washingtons' and civilians' and qur'an"))

输出:

united states' and washington and civilian and qur'an


推荐阅读