【问题标题】:Get paragraph after a certain symbol in Python在Python中某个符号之后获取段落
【发布时间】:2021-08-28 23:24:27
【问题描述】:

我是python初学者。

我有一个大的txt文件,格式如下,由多个单句段落组成:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

****
Sed id placerat magna.

*******
Pellentesque in ex ac urna tincidunt tristique. 

Etiam dapibus faucibus gravida.

我正在尝试仅将输出作为星号段落之后的段落 [每个星号段落至少有4个星号]。

我需要的输出:

Sed id placerat magna.

Pellentesque in ex ac urna tincidunt tristique. 

我正在尝试这样的事情,但我不知道 A] 如何为每个 星号段落 设置最少 4 个星号和 B] 如何设置 星号段落之后的段落。

import re

article_content = [open('text.txt').read() ]

after_asterisk_article_paragraph = []
 
string = "****"
after_asterisk_article_paragraph = string[string.find("****")+4:]

print(*after_asterisk_article_paragraph, sep='\n\n')

再次声明,我刚刚开始使用 Python,请见谅。

【问题讨论】:

    标签: python text extract paragraph


    【解决方案1】:

    您可以读取整个文件并使用一个模式来匹配至少 4 个星号,然后是所有非空行或以 4 个星号开头的行。

    ^\*{4,}((?:\r?\n(?!\s*$|\*{4}).+)*)
    
    • ^\*{4,} 匹配 4 次或更多次 * 从字符串的开头
    • ( 捕获第 1 组
      • (?:非捕获组
        • \r?\n 匹配换行符
        • (?!\s*$|\*{4}).+ 如果不为空或以 4 次开头,则匹配整行 * 使用负前瞻 (?!
      • )* 可选择重复该组
    • )关闭捕获组1

    Regex demo

    例如使用 re.findall 将返回捕获组 1 值:

    import re
    file = open('text.txt', mode='r')
    result = [s.strip() for s in re.findall(r'^\*{4,}((?:\r?\n(?!\s*$|\*{4}).+)*)', file.read(), re.MULTILINE)]
    print(result)
    file.close()
    

    输出

    ['Sed id placerat magna.', 'Pellentesque in ex ac urna tincidunt tristique.']
    

    【讨论】:

    • 有没有办法让每个句子都是一个段落?我似乎无法弄清楚如何在上面的代码中添加这样的内容:split_article_content = [] for element in article_content: split_article_content += re.split("(?<=[.!?])\s+", element)
    • 该代码将在. ! 或? 之后拆分文本并将项目添加到列表split_article_content 这不是您想要的吗?
    • 对不起。相反,我需要代码来拆分',以便输出每段给出一个句子。
    猜你喜欢
    • 2021-10-16
    • 2020-08-30
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2012-02-11
    • 2021-04-30
    • 2014-08-20
    • 2022-12-18
    相关资源
    最近更新 更多