首页 > 解决方案 > 基于 2 正则表达式匹配的正则表达式提取段落

问题描述

我正在研究一个 python 自动化脚本,我想根据正则表达式匹配提取特定段落,但我被困在如何提取段落上。以下是显示我的案例的示例:

解决方案:(一致模式)

我要提取的段落(Inconsistent Pattern)

远程值:x(一致模式)

以下是我目前正在开发的程序,如果有人能启发我,那就太好了!

import re
test= 'Solution\s:'
test1='Remote'
with open('<filepath>', 'r') as extract:
            
            lines=extract.readlines()

            for line in lines:
                x = re.search(test, line)
                y = re.search(test1, line)
                if x is not y:
                    f4.write(line)
                    print('good')
                else:
                    print('stop')

标签: pythonregex

解决方案


这可以使用正则表达式轻松完成,例如:

import re

text = r"""
Solution\s:
The paragraph I
want to extract
Remote
Some useless text here
Solution\s:
Another paragraph
I want to
extract
Remote

"""
m = re.findall(r"Solution\\s:(.*?)Remote", text, re.DOTALL | re.IGNORECASE)
print(m)

wheretext表示一些感兴趣的文本(例如从文件中读取),我们希望从中提取标记模式Solution\s:Remote. 在这里,我们使用 IGNORECASE 搜索,以便识别标记模式,即使拼写不同的大小写。

上面的代码输出:

['\nThe paragraph I\nwant to extract\n', '\nAnother paragraph\nI want to\nextract\n']

阅读https://docs.python.org/3/library/re.html上的 Python re 库文档以获取更多详细信息。


推荐阅读