【问题标题】:How to extract text until it reaches a capital word? Python如何提取文本直到达到大写单词? Python
【发布时间】:2018-06-06 19:02:16
【问题描述】:

这是我的全文:

RETENTION
Liability in excess of the Retention
The Retention shall be borne by the Named Insured and the Insurer shall only be liable for Loss once the Retention has been fully eroded. The Retention shall apply until such time as it has been fully eroded after which no Retention shall apply.
Erosion of the Retention
The Retention shall be eroded by Loss for which the Insurer would be liable under this Policy but for the Retention.

我想提取整个 RETENTION 段落。


这是我提取具有特定单词的句子的代码(这里:保留)。

abc3=([sentence + '.' for sentence in txt_trim_string.split('.') if 'RETENTION' in sentence])

但这给出的输出为:

RETENTION
Liability in excess of the Retention
The Retention shall be borne by the Named Insured and the Insurer shall only be liable for Loss once the Retention has been fully eroded.

我还想包括:

Erosion of the Retention
The Retention shall be eroded by Loss for which the Insurer would be liable under this Policy but for the Retention.

我该怎么做?

【问题讨论】:

  • 你如何定义这里的模式?段落的边界是什么?

标签: python regex nlp


【解决方案1】:

你可以尝试做任何事情,但一个完整的大写单词。要获得完全大写的单词,您可以使用以下正则表达式:([A-Z]){2,}

该表达式捕获两个或多个大写字母相邻的单词。


另一种方法是使用以下正则表达式:[A-Z]?([^A-Z]) 这会选择 0 或 1 个大写字母,后跟任何不是相邻的两个大写字母的字母。

import re
regex = r'[A-Z]?([^A-Z])'
for result in regex.findall(<your text as a string>):
    print(result[1:]) # there will be an extraneous character when a fully capitalized word is encountered

【讨论】:

    【解决方案2】:

    尝试正则表达式:[A-Z]{2,}.*?(?=(?:[A-Z]{2,}|\Z))re.DOTALL 选项以匹配换行符和 .

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多