如何在嵌套结构中存储层次结构信息

How to store hierarchy information in a nested structure

希望你们一切都好!

以下是从文档中提取到 .TXT 文件中的内容。 我想阅读包含以下内容的文本文件:

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

阅读后,我想将其动态存储到 Python 字典中,即如下所示的嵌套列表:

{"file name": { "Main Heading 1": { "Sub-heading 1" : [], "Sub-heading 2" : [] }},
              { "Main Heading 2": { "Sub-heading 1": [ "Sub-Sub-heading 1", "Sub-Sub-heading 2" ] } } }

以上不是固定结构,可以随不同的文件动态变化,我将在循环中进一步自动化该过程。 我是嵌套字典的新手,并且坚持使用“.txt 文件 -> JSON”转换阶段。在这方面的任何帮助都会非常有帮助。谢谢!!

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))

输出

{
    "myfile": {
        "Main Heading 1": {
            "Sub-heading 1": [],
            "Sub-heading 2": []
        },
        "Main Heading 2": {
            "Sub-heading 1": [
                "Sub-Sub-heading 1",
                "Sub-Sub-heading 2"
            ]
        }
    }
}