簡體   English   中英

如何在python中使用正則表達式從文件中提取特定段落?

[英]How to extract a certain paragraph from a file use regex in python?

我的問題是要通過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)

開頭的(?<=\\n\\n)后面有一個回首。 僅當后面有\\n\\n ,它才匹配后面的內容。

最后一位(?=\\n\\n)是超前的,僅當后面有\\n\\n時才匹配前面的東西。

試試看: https : //regex101.com/r/7XnDjS/1

某些Windows文本文件以\\ r \\ n而不是\\ n結尾的行可能很重要。 Python在正則表達式方面有出色的文檔。 只是谷歌“ python regexp”。 您甚至可以在Google上搜索“ 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)

這是我的腳本:

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM