import json
toc = """1 Main Heading 1
1.1 Sub-heading 1
1.2 Sub-heading 2
2 Main Heading 2
2.1 Sub-heading 1
2.1.1 Sub-Sub-heading 1
2.1.2 Sub-Sub-heading 2"""
myfile = 'myfile'
data = {myfile:{}}
for line in toc.splitlines():
levels, title = line.split(' ', maxsplit=1)
levels = levels.rstrip('.').split('.')
if len(levels) == 1:
heading = title
data[myfile][heading] = {}
elif len(levels) == 2:
sub_heading = title
data[myfile][heading][sub_heading] = []
if len(levels) == 3:
data[myfile][heading][sub_heading].append(title)
print(json.dumps(data, indent=4))
output
{
"myfile": {
"Main Heading 1": {
"Sub-heading 1": [],
"Sub-heading 2": []
},
"Main Heading 2": {
"Sub-heading 1": [
"Sub-Sub-heading 1",
"Sub-Sub-heading 2"
]
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…