【发布时间】:2017-08-01 14:24:15
【问题描述】:
我有一个长字符串,它是一个段落,但是句点后没有空格。例如:
para = "I saw this film about 20 years ago and remember it as being particularly nasty. I believe it is based on a true incident: a young man breaks into a nurses\' home and rapes, tortures and kills various women.It is in black and white but saves the colour for one shocking shot.At the end the film seems to be trying to make some political statement but it just comes across as confused and obscene.Avoid."
我正在尝试使用 re.sub 来解决这个问题,但是输出不是我所期望的。
这就是我所做的:
re.sub("(?<=\.).", " \1", para)
我正在匹配每个句子的第一个字符,并且我想在它之前放置一个空格。我的匹配模式是(?<=\.).,它(据说)检查一段时间后出现的任何字符。我从其他 stackoverflow 问题中了解到 \1 匹配最后一个匹配的模式,所以我将替换模式写为\1,一个空格后跟之前匹配的字符串。
这是输出:
"I saw this film about 20 years ago and remember it as being particularly nasty. \x01I believe it is based on a true incident: a young man breaks into a nurses\' home and rapes, tortures and kills various women. \x01t is in black and white but saves the colour for one shocking shot. \x01t the end the film seems to be trying to make some political statement but it just comes across as confused and obscene. \x01void. \x01
re.sub 没有匹配任何前面有句点的字符并在其前面添加一个空格,而是将匹配的字符替换为\x01。为什么?如何在匹配的字符串前添加一个字符?
【问题讨论】:
-
我认为问题应该是 “但是在 一些 个句点之后没有空格。” 因为在第一个句点之后有空格?
-
@shash678 是的,你是对的。我没有这么说,因为在我的情况下,可以有多个空格,我不想让问题变得复杂
-
总是有便宜的答案:
text = text.replace(".", ". ").replace(". " + " ", ". ")(字符串连接是因为堆栈交换占用了双倍空间)。基本上,用句点+空格替换每个句点,用句点+单个空格替换每个句点+空格+空格。不需要正则表达式,也不需要导入任何东西..