我在 python 中有一个很长的字符串,我试图将它分成一个句子列表。这些句子中只有一些缺少标点符号和句子之间的空格。
示例
I have 9 sheep in my garageVideo games are super cool.
我无法找出将两者分开的正则表达式!这让我发疯。
还有正确标点的句子,所以我想我应该制作几种不同的正则表达式模式,每种模式都划分出不同风格的组合。
输入
I have 9 sheep in my garageVideo games are super cool. Some peanuts can sing, though they taste a whole lot better than they sound!
输出
['I have 9 sheep in my garage', 'Video games are super cool.' 'Some peanuts can sing, though they taste a whole lot better than they sound!']
谢谢!
最佳答案
头寸分割:使用regex
模块
我将为您提供“拆分”和“全部匹配”选项。让我们从“拆分”开始。
在许多引擎中,但在 Python 中除外 re
模块中,您可以在零宽度匹配定义的位置处进行分割。
在Python中,要分割一个位置,我会使用Matthew Barnett的杰出的 regex
module ,其功能远远超过了 Python 默认的 re
引擎。这是我在 Python 中的默认正则表达式引擎。
根据您的输入,您可以使用此正则表达式:
(?V1)(?<=[a-z])(?=[A-Z])|(?<=[.!?]) +(?=[A-Z])
请注意,如果您有格式奇怪的首字母缩略词,例如 B. B. C.
,我们需要对此进行调整。
Python 代码示例:
string = "I have 9 sheep in my garageVideo games are super cool. Some peanuts can sing, though they taste a whole lot better than they sound!"
result = regex.split("(?V1)(?<=[a-z])(?=[A-Z])|(?<=[.!?]) +(?=[A-Z])", string)
print(result)
输出:
['I have 9 sheep in my garage',
'Video games are super cool.',
'Some peanuts can sing, though they taste a whole lot better than they sound!']
说明
-
(?V1)
指示引擎使用新行为,我们可以在零宽度匹配上进行分割。 -
(?<=[a-z])(?=[A-Z])
匹配后向(?<=[a-z])
的位置可以断言前面是一个小写字母和前瞻(?=[A-Z])
可以断言后面是一个大写字母。 -
|
或者... -
(?<=[.!?]) +(?=[A-Z])
匹配一个或多个空格+
回溯在哪里(?<=[.!?])
可以断言前面是一个点、一声、问号和一个空格,而前瞻(?=[A-Z])
的位置可以断言后面的内容是大写字母。
选项 2:使用 findall
(再次使用 regex
模块)
由于“拆分”和“全部匹配”操作是同一枚硬币的两面,因此您可以这样做:
print(regex.findall(r".+?(?:(?<=[.!?])|(?<=[a-z])(?=[A-Z]))",string))
同样,这不适用于 re
(这将跳过第二句开始的 V
Video
)。
关于python - 根据标点符号或驼峰式大小写分割句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986995/