如何使用python中的正则表达式从文件中提取特定段落?

如何使用python中的正则表达式从文件中提取特定段落?,python,regex,extract,paragraph,Python,Regex,Extract,Paragraph,我的问题是通过Python中的正则表达式从文件中提取某个段落(例如,通常是中间段落) 示例文件如下所示: poem = """The time will come when, with elation, you will greet yourself arriving at your own door, in your own mirror, and each will smile at the other's welcome, and say, sit here. Eat. You will

我的问题是通过Python中的正则表达式从文件中提取某个段落(例如,通常是中间段落)

示例文件如下所示:

poem = """The time will come
when, with elation,
you will greet yourself arriving
at your own door, in your own mirror,
and each will smile at the other's welcome,
and say, sit here. Eat.
You will love again the stranger who was your self.
Give wine. Give bread. Give back your heart
to itself, to the stranger who has loved you

all your life, whom you ignored
for another, who knows you by heart.
Take down the love letters from the bookshelf,

the photographs, the desperate notes,
peel your own image from the mirror.
Sit. Feast on your life."""

如何提取这首诗的第二段(意思是“你的一生……书架”),使用python中的正则表达式?

向前看,向后看:

(?<=\n\n).+(?=\n\n)

(?某些Windows文本文件必须以\r\n而不仅仅是\r\n结尾。
Python有关于正则表达式的优秀文档。只需谷歌“Python regexp”。您甚至可以谷歌“perl regexp”,因为Python从perl复制了regexp;-)
获取第二段文本的一种方法是使用()在两组两个或多个行尾之间获取文本,如下所示:

myPattern = re.compile('[^\r\n]+\r?\n\r?\n+([^\r\n]+)\r?\n\r?\n.*')
secondPara = myPattern.sub("\\1", content)
然后像这样使用它:

myPattern = re.compile('[^\r\n]+\r?\n\r?\n+([^\r\n]+)\r?\n\r?\n.*')
secondPara = myPattern.sub("\\1", content)
以下是我的脚本:

schumack@linux2 137> ./poem2.py
secondPara: all your life, whom you ignored for another, who knows you by heart. Take down the love letters from the bookshelf,

使用组捕获并尝试以下操作:

import re


pattern=r'^(all.*bookshelf[,\s])'

second=re.search(pattern,poem,re.MULTILINE | re.DOTALL)
print(second.group(0))

只要捕获
\n\n
之间的任何内容即可。我现在正在努力理解第二段的模式。需要帮助@BurhanKhalid您能为我提供捕获介于两个之间的任何内容的特定代码吗\n\n?非常感谢你的帮助。我添加了如下代码:paragration=re.match(r')(?@希望您必须使用
search
,而不是
match
。另外,在返回值上调用
group(0)
,以获得匹配的字符串。如下所示:paragration=re.search(r')(?result=paragration.group(0)AttributeError:“非类型”对象没有属性“组”它确实起作用:这可能不起作用的一个原因可能是您正在使用Windows,其中新行由
\r\n
表示,但我没有Windows PC,所以我不确定。请尝试将
\n\n
替换为
\r\n\r\n
@hoperoseThank you@Ken schumak。否没关系,运行结果返回了全部内容。我不知道为什么