Python:句子分割产生一个空格

Python:句子分割产生一个空格,python,python-3.x,Python,Python 3.x,所以我有一些句子,比如: The window is over there. The lamp is on. The fire is burning. 当我使用拆分“.”将其拆分,然后使用换行符将其合并时,它将丢失 然后我尝试了regex-like?显然没有处理特殊情况,即一段时间后没有空间,为什么不这样做: >>> s = 'The window is over there. The lamp is on. The fire is burning.' >>>

所以我有一些句子,比如:

The window is over there. The lamp is on. The fire is burning.
当我使用拆分“.”将其拆分,然后使用换行符将其合并时,它将丢失


然后我尝试了regex-like?显然没有处理特殊情况,即一段时间后没有空间,为什么不这样做:

>>> s = 'The window is over there. The lamp is on. The fire is burning.'
>>> print s.replace('. ', '.\n')
The window is over there.
The lamp is on.
The fire is burning.

有几种处理拆分输入的方法:拆分后进行剥离、使用正则表达式拆分或使用简单搜索

第一个选项可能是最直观的:您可以像以前一样在点上拆分字符串,然后剥离生成的字符串以删除任何空白并恢复尾随点。在Python中:

sentences = input.split('.')
sentences = [s.strip() + '.' for s in sentences if s]
print sentences.join('\n')
第二种更简单的方法是简单地替换“.”带“.”\n“

print input.replace('. ', '.\n')
这将适用于您的输入,但如果有人使用两个空格分隔一些人喜欢的句子,则将失败

最后一种也是最灵活的方法是使用正则表达式根据点和空格的组合进行拆分:

import re
sentences = re.split('(?<=\.)\s*', input)
print sentences.join('\n')

请注意正则表达式的重要区别:我使用\s*使用所有可能的空格。这在有两个或多个空格的情况下很重要,或者根本没有空格。

当然,我会用这个;你的最后一句没有。是的,你是对的。好吧,假设每个句子都是。终止后,我们始终可以添加一个。在表达式的末尾:。否则,我的解决方案不包括这种情况。您的正则表达式解决方案对我来说很好
>>> s = 'The window is over there. The lamp is on. The fire is burning.'
>>> print s.replace('. ', '.\n')
The window is over there.
The lamp is on.
The fire is burning.
sentences = input.split('.')
sentences = [s.strip() + '.' for s in sentences if s]
print sentences.join('\n')
print input.replace('. ', '.\n')
import re
sentences = re.split('(?<=\.)\s*', input)
print sentences.join('\n')