基于 2 个正则表达式匹配的正则表达式提取段落

我正在开发一个 python 自动化脚本,我想根据正则表达式匹配提取特定段落,但我不知道如何提取该段落。以下是我的案例的示例:


解决方案:(一致模式)


我要提取的段落(不一致模式)


远程值: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')


智慧大石
浏览 75回答 1
1回答

慕桂英3389331

这可以使用正则表达式轻松完成,例如:import retext = r"""Solution\s:The paragraph Iwant to extractRemoteSome useless text hereSolution\s:Another paragraphI want toextractRemote"""m = re.findall(r"Solution\\s:(.*?)Remote", text, re.DOTALL | re.IGNORECASE)print(m)其中text表示一些感兴趣的文本(例如,从文件中读取),我们希望从中提取哨兵模式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 库文档了解更多详细信息。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python