Aufteilen der Textdatei in Abschnitte mit einem speziellen Trennzeichen - Python

Ich habe eine Eingabedatei als solche:

This is a text block start
This is the end

And this is another
with more than one line
and another line.

Die gewünschte Aufgabe besteht darin, die Dateien nach Abschnitten zu lesen, die durch eine spezielle Zeile begrenzt sind. In diesem Fall handelt es sich um eine leere Zeile, z. [aus]:

[['This is a text block start', 'This is the end'],
['And this is another','with more than one line', 'and another line.']]

Ich habe auf diese Weise die gewünschte Ausgabe erhalten:

def per_section(it):
    """ Read a file and yield sections using empty line as delimiter """
    section = []
    for line in it:
        if line.strip('\n'):
            section.append(line)
        else:
            yield ''.join(section)
            section = []
    # yield any remaining lines as a section too
    if section:
        yield ''.join(section)

Aber wenn die Sonderlinie eine Linie ist, die mit beginnt# z.B.:

# Some comments, maybe the title of the following section
This is a text block start
This is the end
# Some other comments and also the title
And this is another
with more than one line
and another line.

Ich muss das tun:

def per_section(it):
    """ Read a file and yield sections using empty line as delimiter """
    section = []
    for line in it:
        if line[0] != "#":
            section.append(line)
        else:
            yield ''.join(section)
            section = []
    # yield any remaining lines as a section too
    if section:
        yield ''.join(section)

Wenn ich das erlauben würdeper_section() Um einen Begrenzer-Parameter zu haben, könnte ich Folgendes versuchen:

def per_section(it, delimiter== '\n'):
    """ Read a file and yield sections using empty line as delimiter """
    section = []
    for line in it:
        if line.strip('\n') and delimiter == '\n':
            section.append(line)
        elif delimiter= '\#' and line[0] != "#":
            section.append(line)
        else:
            yield ''.join(section)
            section = []
    # yield any remaining lines as a section too
    if section:
        yield ''.join(section)

Aber gibt es eine Möglichkeit, dass ich nicht alle möglichen Trennzeichen fest codiere?

Antworten auf die Frage(3)

Ihre Antwort auf die Frage