我有一堆文档,我有兴趣查找提及临床试验的内容。这些总是由全部大写的字母表示(例如 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
输出:
[('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/