【问题标题】:Python regex - How to look for an arbitrary number of sentences after a digit?Python regex - 如何在数字后查找任意数量的句子?
【发布时间】:2018-07-06 14:44:11
【问题描述】:

假设我们有以下字符串:“1. Sentence 1. Sentence 2? Sentence 3!”。 我将如何寻找(并以字符串形式返回)匹配以下所有情况的模式:

  • "1. Sentence 1."
  • "1. Sentence 1. Sentence 2?"
  • "1. Sentence 1. Sentence 2? Sentence 3!"

图案前面总是有一个数字, 但后面可以有任意数量的句子。 到目前为止我尝试过的是

pattern = re.compile("\d.(\s[A-Ö][^.!?]+[.!?])+?")   

assignmentText = "".join(pattern.findall(assignment))

join 方法是一个丑陋的 hack,用于从findall 返回的列表中提取字符串,因为list[0] 似乎不起作用(我知道只有一个 str在列表中)。 但是,我只收到第一句话,前面没有数字。

如何解决这个问题?

【问题讨论】:

  • 您的意思是将大写字母与[A-Ö] 匹配吗?它matches all lowercase ASCII letters, too.
  • 请同时发布您的预期输出
  • 预期输出是问题中列出的字符串之一。至于@Wiktor Stribiżew 的问题,是的,我希望句子在语法上正确,因为第一个字母应该大写。

标签: python regex python-3.x pattern-matching


【解决方案1】:

您可以使用(?:(?:\d+\.\s+)?[A-Z].*?[.!?]\s*)+

import re
print(re.findall(r'(?:(?:\d+\.\s+)?[A-Z].*?[.!?]\s*)+', '1. Sentence 1. Sentence 2? Sentence 3!'))

这个输出:

['1. Sentence 1. Sentence 2? Sentence 3!']

或者,如果您更喜欢将它们分隔为列表中的 3 个不同项目:

import re
print(re.findall(r'(?:(?:\d+\.\s+)?[A-Z].*?[.!?])', '1. Sentence 1. Sentence 2? Sentence 3!'))

这个输出:

['1. Sentence 1.', 'Sentence 2?', 'Sentence 3!']

【讨论】:

  • 这似乎成功了。然后我可以使用join 来提取实际的字符串。
  • 请注意[A-Z] 仅匹配 ASCII 大写字母。
猜你喜欢
  • 2020-06-26
  • 2011-04-18
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多