You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python正则表达式提取句子时首字母小写问题求助

问题原因分析

你的问题根源在于两个关键错误:

  1. 正则表达式消耗了下一个句子的首字母
    你写的正则([A-Z1-9]{1}.+?\.)\s*[A-Z|1-9]中,捕获组后的\s*[A-Z|1-9]会实际匹配并消耗下一个句子的首字母(比如第一个句子结尾句号后的空格+T,这个T会被正则吃掉)。这导致下一次匹配时,指针直接跳到了T的下一个字符(o),而不是停在T的位置。

  2. 多余的re.IGNORECASE标志放大了问题
    因为添加了re.IGNORECASE,正则里的[A-Z1-9]会匹配大小写字母和数字。当指针跳到小写的o时,正则会认为这符合句子开头的条件,于是提取出以o开头的句子,自然首字母就变成小写了。

另外还有个小细节错误:[A-Z|1-9]里的|是普通字符(不是逻辑或),应该改成[A-Z1-9],否则会把|也当作匹配目标之一。

修正后的代码

我们可以用正向预查(?=...))替代消耗字符的匹配,这样正则只会检查句号后是否紧跟大写字母/数字,不会消耗该字符;同时去掉re.IGNORECASE标志,严格匹配大写开头的规则:

import re

txt = """ DETROIT—Alter Road runs northwest along this city’s border. To the east is Grosse Pointe Park, an upscale suburb dotted with grand old mansions built in the auto industry’s heyday. To the west is the city of Detroit, lined with abandoned houses and empty lots. On the east side of the street, getting a mortgage to buy a home is a breeze. On the west side, it is hardly worth trying. Detroit is making a comeback after years of decline that led to a bankruptcy filing in 2013. But large swaths of the city are left behind, starved of the housing credit needed to revive them. No purchase mortgages were made last year in almost a third of Detroit’s census tracts, and fewer than five each in another third, according to data from LendingPatterns.com, a mortgage-data analysis tool. """

# 修正后的正则:用正向预查保留下一个句子的首字母
r1 = re.findall(r"([A-Z1-9].+?\.)\s*(?=[A-Z1-9])", txt, flags=re.MULTILINE)

# 打印提取的句子
for sentence in r1:
    print(sentence)
补充说明
  • 正向预查(?=[A-Z1-9])的作用是:验证当前位置后是否是大写字母/数字,但不会移动匹配指针,这样下一次匹配能从下一个句子的首字母开始。
  • 去掉re.IGNORECASE后,正则严格匹配以大写字母或数字开头的句子,完全符合你最初的规则。
  • [A-Z1-9]{1}可以简化为[A-Z1-9],因为{1}是正则的默认行为,无需显式写出。

内容的提问来源于stack exchange,提问作者Elior Sastiel

火山引擎 最新活动