我的文件包含如下所示的行:
saldkfjaslk
asdlkfja
alsdkfjlk
aslkda;kdfsdlkfaj
sladkfjalskdfjlaskd
sldkfaj
lsadkfj
qwewrewst
se0polkjlkj
lpoerlwoej
alskdjf
asldkfjljlkjlk
sadlkfa
我想将以字符(不是空格)开头的行组合在一起,这些行以空格开头的连续行。我还想省略下一行不以空格开头的行。使用上面示例的所需输出如下所示:
[('saldkfjaslk', 'asdlkfja', 'alsdkfjlk'),
('sladkfjalskdfjlaskd', 'sldkfaj', 'lsadkfj'),
('lpoerlwoej', 'alskdjf', 'asldkfjljlkjlk')]
如何在Python中解析此文件?
答案 0 :(得分: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