import re
ss = '''Princess Maria Amelia of Brazil (1831–1853)
was the daughter of Dom Pedro I,
founder of Brazil's independence and its first emperor,
and Amelie of Leuchtenberg.
The only child from her father's second marriage,
Maria Amelia was born in France
following Pedro I's 1831 abdication in favor of his son Dom Pedro II.
Before Maria Amelia was a month old, Pedro I left for Portugal
to restore its crown to his eldest daughter Dona Maria II.
He defeated his brother Miguel I (who had usurped Maria II's throne),
only to die a few months later of tuberculosis.
'''
def select_lines(input,regx = re.compile('((?:^.+\n)+)',re.MULTILINE)):
return [x.splitlines() for x in regx.findall(input)]
for sl in select_lines(ss):
print sl
print
結果
['Princess Maria Amelia of Brazil (1831\x961853)']
['was the daughter of Dom Pedro I,', "founder of Brazil's independence and its first emperor,"]
['and Amelie of Leuchtenberg.']
["The only child from her father's second marriage,", 'Maria Amelia was born in France', "following Pedro I's 1831 abdication in favor of his son Dom Pedro II."]
['Before Maria Amelia was a month old, Pedro I left for Portugal', 'to restore its crown to his eldest daughter Dona Maria II.', "He defeated his brother Miguel I (who had usurped Maria II's throne),", 'only to die a few months later of tuberculosis.']
[['2', '3'], ['5', '6', '7', '8'], ['11']]
リストを操作する別の方法:
li = [ '', '2', '3', '', '5', '6', '7', '8', '', '', '11']
lo = ['5055','','','2','54','87','','1','2','5','8','','']
lu = ['AAAAA','BB','','HU','JU','GU']
def selines(L):
ye = []
for x in L:
if x:
ye.append(x)
elif ye:
yield ye ; ye = []
if ye:
yield ye
for lx in (li,lo,lu):
print lx
print list(selines(lx))
print
結果
['', '2', '3', '', '5', '6', '7', '8', '', '', '11']
[['2', '3'], ['5', '6', '7', '8'], ['11']]
['5055', '', '', '2', '54', '87', '', '1', '2', '5', '8', '', '']
[['5055'], ['2', '54', '87'], ['1', '2', '5', '8']]
['AAAAA', 'BB', '', 'HU', 'JU', 'GU']
[['AAAAA', 'BB'], ['HU', 'JU', 'GU']]