【问题标题】:How to extract a certain paragraph from a file use regex in python?如何从文件中提取某个段落在python中使用正则表达式?
【发布时间】:2017-10-05 00:01:04
【问题描述】:

我的问题是通过 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 之间的任何内容。
  • 我现在正与第二段的模式作斗争。需要帮助!
  • @BurhanKhalid 你能给我提供具体的代码来捕获两个 \n\n 之间的任何东西吗?非常感谢

标签: python regex extract paragraph


【解决方案1】:

使用组捕获并尝试一下:

import re


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

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

【讨论】:

    【解决方案2】:

    使用积极的前瞻和后视:

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

    开头的(?&lt;=\n\n) 有一个后视。只有后面有\n\n才匹配后面的东西。

    最后一位(?=\n\n) 是一个前瞻,如果它之后有\n\n,它只匹配它之前的东西。

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

    【讨论】:

    • 感谢您的帮助。我像这样添加了您的代码:paragraph =re.match(r'(?
    • @hoperose 你必须使用search 而不是match。另外,在返回值上调用group(0)来获取匹配的字符串。
    • 像这样:paragraph = re.search(r'(?
    • result=paragraph.group(0) AttributeError: 'NoneType' object has no attribute 'group'
    • 它确实有效:repl.it/MD7v/0 这可能无效的一个原因可能是您使用的是 Windows,其中新行由 \r\n 表示,但我没有 Windows PC,所以我不确定。尝试将\n\ns 替换为\r\n\r\n。 @hoperose
    【解决方案3】:

    某些 Windows 文本文件以 \r\n 而不是仅 \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)
    

    这是我的脚本:

    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,
    

    【讨论】:

    • 谢谢@肯舒马克。尽管如此,运行结果还是返回了全部内容。我不知道为什么
    猜你喜欢
    • 2021-02-05
    • 2016-04-02
    • 2014-08-05
    • 1970-01-01
    • 2012-01-17
    • 2015-01-16
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多