位置拆分:使用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 模块)
由于“Split”和“Match All”操作是同一枚硬币的两个面,您可以这样做:
print(regex.findall(r".+?(?:(?<=[.!?])|(?<=[a-z])(?=[A-Z]))",string))
同样,这不适用于re(它将跳过以第二句Video 开头的V)。