Dividindo arquivo de texto em seção com linha delimitadora especial - python
Eu tenho um arquivo de entrada como tal:
This is a text block start
This is the end
And this is another
with more than one line
and another line.
A tarefa desejada é ler os arquivos por seção delimitada por alguma linha especial; nesse caso, é uma linha vazia, por exemplo [Fora]:
[['This is a text block start', 'This is the end'],
['And this is another','with more than one line', 'and another line.']]
Eu tenho conseguido a saída desejada ao fazer isso:
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)
Mas se a linha especial é uma linha que começa com#
por exemplo.:
# 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.
Eu tenho que fazer isso:
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)
Se eu permitir oper_section()
para ter um parâmetro delimitador, eu poderia tentar o seguinte:
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)
Mas existe uma maneira de eu não codificar todos os delimitadores possíveis?