【问题标题】:Regext to match capitalized word, and the surrounding +- 4 words正则表达式匹配大写单词,以及周围的 +- 4 个单词
【发布时间】:2018-10-11 07:41:57
【问题描述】:

我有一堆文件,我有兴趣查找提及临床试验的内容。这些始终由全部大写的字母表示(例如 ASPIRE)。我想匹配所有大写的任何单词,大于三个字母。我还想要周围的 +- 4 个单词作为上下文。

以下是我目前拥有的。它有点工作,但没有通过下面的测试。

import re
pattern = '((?:\w*\s*){,4})\s*([A-Z]{4,})\s*((?:\s*\w*){,4})'
line = r"Lorem IPSUM is simply DUMMY text of the printing and typesetting INDUSTRY."
re.findall(pattern, line)

【问题讨论】:

  • 您能否在问题中包含预期结果。

标签: python regex


【解决方案1】:

您可以在 python 中使用此代码,分两步完成。首先,我们将输入拆分为 4 个以上的大写字母,然后在匹配的两边找到最多 4 个单词。

import re

str = 'Lorem IPSUM is simply DUMMY text of the printing and typesetting INDUSTRY'

re1 = r'\b([A-Z]{4,})\b'
re2 = r'(?:\s*\w+\b){,4}'

arr = re.split(re1, str)

result = []

for i in range(len(arr)):
    if i % 2:
        result.append( (re.search(re2, arr[i-1]).group(), arr[i], re.search(re2, arr[i+1]).group()) )


print result

Code Demo

输出:

[('Lorem', 'IPSUM', ' is simply'), (' is simply', 'DUMMY', ' text of the printing'), (' text of the printing', 'INDUSTRY', '')]

【讨论】:

    【解决方案2】:

    以下正则表达式对您有用吗?

    (\b\w+\b\W*){,4}[A-Z]{3,}\W*(\b\w+\b\W*){,4}
    

    在这里测试:https://regex101.com/r/nTzLue/1/

    【讨论】:

    • 在 OP 的输入 Lorem IPSUM is simply DUMMY text of the printing and typesetting INDUSTRY 中找不到此正则表达式 IPSUM
    【解决方案3】:

    在左侧,您可以匹配任何单词字符\w+ 一次或多次,然后匹配任何非单词字符\W+ 一次或多次。将这两个组合在一个非捕获组中,然后重复 4 次 {4} 就像 (?:\w+\W+){4}

    然后在一组([A-Z]{3,})中捕获3个或更多大写字符。

    或者右侧你可以将单词和非单词字符的匹配转为左侧匹配的内容(?:\W+\w+){4}

    (?:\w+\W+){4}([A-Z]{3,})(?:\W+\w+){4}

    捕获的组将包含您的大写单词,而捕获组将包含周围的单词。

    【讨论】:

    • 在 OP 的输入 Lorem IPSUM is simply DUMMY text of the printing and typesetting INDUSTRY 中,尽管有 3 个这样的大写字母单词,但这个正则表达式只找到一个匹配项。
    【解决方案4】:

    这应该可以完成工作:

    pattern = '(?:(\w+ ){4})[A-Z]{3}(\w+ ){5}'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 2012-01-06
      相关资源
      最近更新 更多