Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - How to store hierarchy information in a nested structure

Hope you all are doing great!

The below is an extract from a document into a .TXT file. I wish to read the text file with the below contents:

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

Upon reading, I want to DYNAMICALLY store it into a Python dictionary i.e. Nested lists like below:

{"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" ] } } }

Above is not a fixed structure and can be dynamic with different files and I shall be further automating the process in a loop. I am new to nested dictionary and am stuck with the ".txt file -> JSON" conversion stage. Any help on this regard would be very helpful. Thanks!!

question from:https://stackoverflow.com/questions/65840714/how-to-store-hierarchy-information-in-a-nested-structure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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"
            ]
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...