Let's say I have the following text:
text = '''
test1:
aaa: aaa
test2:
bbb:bbb
test3:
ccc:ccc
eee:eee
test2:
ddd:ddd
'''
I would like to parse that text and create a dict in which the keys are the lines which have zero leading spaces and the value a list of remaining lines below of each key. In case there are two same keys like 'test2' then a second list should be assigned under the same key. So my end result dict should be like the following:
{
"test1": [
[" aaa: aaa"],
],
"test2": [
[" bbb: bbb"],
[" ddd: ddd"],
],
"test3": [
[
[" ccc:ccc", " eee:eee"],
]
],
"test": [
[" ddd:ddd"],
]
}
Util now I wrote the following code but need some help to finish it:
parsed = {}
proj = None
prev_proj = None
lines = []
for line in text.splitlines()[1:-1]:
leading_whitespaces = len(line) - len(line.lstrip())
if leading_whitespaces == 0 and (re.match(r'^[a-z_]', line)):
proj = line.split(':')[0]
if not parsed and len(lines) == 0:
parsed[proj] = []
parsed[proj].append(lines)
elif len(lines) > 0 and parsed:
parsed[prev_proj] = []
parsed[prev_proj].append(lines)
lines = []
prev_proj = proj
else:
lines.append(line)