python - 第一个字符被删除(正则表达式)

标签 python regex python-3.x

我有这个正则表达式: (?<=[.!?])\s[A-Z] 我在这段文本上运行它:

The engineering plant, weapon and electronic systems, galley, and multitudinous other
equipment required to transform the new hull into an operating and habitable warship are
installed and tested. The prospective commanding officer, ship's officers, the petty
officers, and seamen who will form the crew report for training and intensive
familiarization with their new ship.

它产生:

he engineering plant, weapon and electronic systems, galley, and multitudinous other
equipment required to transform the new hull into an operating and habitable warship are
installed and tested.
he prospective commanding officer, ship's officers, the petty officers, and seamen who
will form the crew report for training and intensive familiarization with their new ship.

如您所见,它删除了句子的第一个字母。这并不是因为它们是大写的(我测试过)。

如何修复它,使其不会删除句子的第一个字母?

(我使用的是 Python 3)

我使用了 re.split(),然后打印了数组,用换行符分隔每个值

最佳答案

您的正则表达式匹配一个空格字符和一个大写 ASCII 字母,但前提是它们前面有一个点、感叹号或问号。

当您使用它来拆分文本时,大写字母将成为用于拆分的分隔符的一部分,因此会被删除。

将正则表达式更改为

(?<=[.!?])\s(?=[A-Z])

并且该字母不会成为匹配的一部分。

但是请注意两件事:

  1. 仅当新句子以 ASCII 字母开头时,此功能才有效。对于大多数英语句子,您可能没问题,但对于其他语言肯定不行。
  2. 如果您的文本包含缩写,可能会出现一些错误拆分:Mr.史密斯博士。琼斯将被一分为二。

关于python - 第一个字符被删除(正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14059506/

相关文章:

python - Python/Pygame 中用于识别按键的正则表达式

regex - OCLinEcore 和 Regex 创建有效的 IPv4 字符串

regex - 帮助使用正则表达式 - 提取文本

android - Android 上的 Pygame/Kivy?

Python sorted() 关键函数怪异

python - 如何在 Python 上使用 "pip"安装 psycopg2?

python - 装饰器更改返回类型时键入函数

python - 匹配列并 append 到数据框,Python 3.6

python - 在 Python 3 CGI 中使用 matplotlib

python - 为什么你可以将列表切片超过总索引计数,但不能直接检索所述索引?