python - 正则表达式匹配大写单词,以及周围的 +- 4 个单词

标签 python regex

我有一堆文档,我有兴趣查找提及临床试验的内容。这些总是由全部大写的字母表示(例如 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 中使用此代码,分两步完成。首先,我们将输入拆分为 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', '')]

关于python - 正则表达式匹配大写单词,以及周围的 +- 4 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50113590/

相关文章:

C# 使用正则表达式获取多个匹配项

java - 正则表达式查找持续时间

python - 极地 python : split string in lazyframe column into new columns

python - 二维数组到数据框中的两列

python - 如何构建自动更新的机器学习系统(智能系统)?

python - 在 openpyxl 的优化阅读器中使用 ws.iter_rows 迭代一系列行

python - django.core.exceptions.ImproperlyConfigured : The included URLconf '' does not appear to have any patterns in it

javascript - 如何从以某个单词结尾的字符串中获取id(正则表达式)

javascript - 所有 JavaScript 正则表达式都适用于 .NET 吗?

python - 确定从 Python 中的正则表达式搜索返回的组数