Python:删除标点符号之间的空格

Python: Removing spaces between punctuation with positive lookahead

我正在尝试删除句子中标点字符之间出现的空格。为了说明这一点,数据集有很多字符串,如下所示:

 "This is a very nice text : ) : ) ! ! ! ."

但我希望它们看起来像这样:

 "This is a very nice text :):)!!!."

我想使用 RegEx positive lookahead 来做到这一点,但有人可以告诉我如何在 Python 中做到这一点。我现在有了代码,但它通过添加额外的空格与我想要的完全相反:

 string = re.sub('([.,!?()])', r' ', string)

原则上,您可以在标点字符(您捕获的)之间找到 space(spaces?)并仅替换捕获的标点字符:

string = re.sub('([:.,!?()]) ([:.,!?()])', r'', string)

但是,这会导致

This is a very nice text :) :) !! !.

因为 re.sub 不考虑 重叠匹配


因此,您需要使用零宽度前瞻和后视 - 它们不计入匹配项,因此匹配部分只是 space 字符,然后我们将其替换为空字符串。

string = re.sub('(?<=[:.,!?()]) (?=[:.,!?()])', '', string)

结果是'This is a very nice text :):)!!!.'

您可以使用如下正则表达式:

(?<=[.:,!?()])\s+(?=[.:,!?()])

此处括号之间的两部分是look behindlook aheads,寻找标点符号。然后我们匹配 \s+ (一个或多个空格部分)。然后我们可以用空字符串替换它。例如:

import re

rgx = re.compile(r'(?<=[.:,!?()])\s+(?=[.:,!?()])')

rgx.sub('', 'This is a very nice text : ) : ) ! ! ! .')

然后生成:

>>> rgx.sub('', 'This is a very nice text : ) : ) ! ! ! .')
'This is a very nice text :):)!!!.'