1

我有一个文件,其行如下所示:

saldkfjaslk
    asdlkfja
    alsdkfjlk
aslkda;kdfsdlkfaj
sladkfjalskdfjlaskd
    sldkfaj
    lsadkfj
qwewrewst
se0polkjlkj
lpoerlwoej
    alskdjf
    asldkfjljlkjlk
sadlkfa

我想将以字符(不是空格)开头的行与以空格开头的后续行组合在一起。我还想省略下一行不以空格开头的行。使用上述示例的所需输出如下所示:

[('saldkfjaslk', 'asdlkfja', 'alsdkfjlk'),
 ('sladkfjalskdfjlaskd', 'sldkfaj', 'lsadkfj'),
 ('lpoerlwoej', 'alskdjf', 'asldkfjljlkjlk')]

如何在 Python 中解析这个文件?

4

1 回答 1

6
>>> regex = re.compile(r"^\S.*(?:\n\s.*)+", re.MULTILINE)
>>> [tuple(match.split()) for match in regex.findall(s)]
[('saldkfjaslk', 'asdlkfja', 'alsdkfjlk'), 
 ('sladkfjalskdfjlaskd', 'sldkfaj', 'lsadkfj'), 
 ('lpoerlwoej', 'alskdjf', 'asldkfjljlkjlk')]

解释:

^    # Start of line
\S   # Match a non-whitespace character
.*   # Match the rest of the line
(?:  # Match...
 \n  #  a newline character
 \s  #  a whitespace character
 .*  #  and the rest of the line
)+   # once or more
于 2013-02-04T15:37:34.750 回答