我有这个正则表达式: (?<=[.!?])\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])
并且这封信不会成为匹配的一部分。
不过,请注意两件事:
- 这仅在新句子以 ASCII 字母开头时有效。对于大多数英语句子,您可能没问题,但对于其他语言肯定不行。
- 如果您的文本包含缩写,可能会有一些错误的拆分:
Mr.史密斯和博士。琼斯将一分为二。
