Самый простой подход - пройти по этим строкам (при условии, что у вас есть список строк или файл, или разбить строку на список строк), пока вы не увидите строку, которая просто '\n'
, а затем проверить строка начинается с '- '
(с использованием строкового метода startswith
) и обрезает его, сохраняя результат, пока не найдете другую пустую строку. Например:
# if you have a single string, split it into lines.
L = s.splitlines()
# if you (now) have a list of lines, grab an iterator so we can continue
# iteration where it left off.
it = iter(L)
# Alternatively, if you have a file, just use that directly.
it = open(....)
# Find the first empty line:
for line in it:
# Treat lines of just whitespace as empty lines too. If you don't want
# that, do 'if line == ""'.
if not line.strip():
break
# Now starts data.
for line in it:
if not line.rstrip():
# End of data.
break
if line.startswith('- '):
data.append(line[:2].rstrip())
else:
# misformed data?
raise ValueError, "misformed line %r" % (line,)
Отредактировано: так как вы уточняете, что вы хотите сделать, вот обновленная версия циклов. Он больше не зацикливается дважды, а собирает данные до тех пор, пока не встретит «плохую» строку, и либо сохраняет, либо отбрасывает собранные строки, когда встречает разделитель блоков. Ему не нужен явный итератор, потому что он не перезапускает итерацию, поэтому вы можете просто передать ему список (или любой итеративный) строк:
def getblocks(L):
# The list of good blocks (as lists of lines.) You can also make this
# a flat list if you prefer.
data = []
# The list of good lines encountered in the current block
# (but the block may still become bad.)
block = []
# Whether the current block is bad.
bad = 1
for line in L:
# Not in a 'good' block, and encountering the block separator.
if bad and not line.rstrip():
bad = 0
block = []
continue
# In a 'good' block and encountering the block separator.
if not bad and not line.rstrip():
# Save 'good' data. Or, if you want a flat list of lines,
# use 'extend' instead of 'append' (also below.)
data.append(block)
block = []
continue
if not bad and line.startswith('- '):
# A good line in a 'good' (not 'bad' yet) block; save the line,
# minus
# '- ' prefix and trailing whitespace.
block.append(line[2:].rstrip())
continue
else:
# A 'bad' line, invalidating the current block.
bad = 1
# Don't forget to handle the last block, if it's good
# (and if you want to handle the last block.)
if not bad and block:
data.append(block)
return data
И вот оно в действии:
>>> L = """hello
...
... - x1
... - x2
... - x3
...
... - x4
...
... - x6
... morning
... - x7
...
... world""".splitlines()
>>> print getblocks(L)
[['x1', 'x2', 'x3'], ['x4']]