Python:从文本文件中提取值以创建嵌套字典

Python: Extract values from a text file to create nested dictionary

我有一个包含多个子索引对象的非常杂乱无章的文本文件,如下所示:

1:
Name of Object 1

Sub-index 0: 
Scale: Q0
Unit: Percent
Description: Object 1 does this

2:
Object 2 yo

Sub-index 0: 
Scale: Q0
Unit: Percent
Description: Something important

Sub-index 1: 
Scale: 0.125
Unit: Percent
Description: Object 2 does that

我想提取这些对象的名称、比例和描述并将它们制作成字典。像这样:

ObjectDict = {
    1: ['Name of Object 1', 'Q0', 'Object 1 does this'],
    2: {
        0: ['Object 2 yo', 'Q0', 'Something important'],
        1: ['Object 2 yo', '0.125', 'Object 2 does that']
    }
}

我可以通过这样做来提取字典键:

for line in textfile:
    a = line.replace(':', '')
    if b.isnumeric():
        # this is 1 key

我可以通过执行以下操作“可能”提取对象的比例和描述值:

if 'Scale' in line: # Store the value
if 'Description' in line: # Store the value

但是,这仅在对象只有 1 个子索引时才有效。对于像对象 2 这样的多子索引对象,我还不知道该怎么做。在 Python 3.7 中有没有好的方法来做到这一点?谢谢!

编辑:我在上面选择的字典格式只是一个例子。任何其他格式的字典都可以。我只是想从一个杂乱无章的文件中提取必要的数据并更妥善地存储它,以便其他文件可以访问它们。

如果你对 txt 文件中的每个对象都使用字典,你可以遍历 txt 文件的行并使用一些 python 内置函数,如 readlines()startswith() 来做你想做的事情想要。

f = open('sample.txt')
lines = f.readlines()
d = {}
for i,line in enumerate(lines):
    if line[:-2].isnumeric():
        ind =  line[:-2]
        name = lines[i+1].replace('\n', '')
        if not ind in d:
            d[ind] = {}

    if line.startswith('Sub-index'):
        sub_ind = line.split()[-1].split(':')[0]
        if not sub_ind in d[ind]:
            d[ind][sub_ind] = []
            d[ind][sub_ind].append(name)

    if line.startswith('Scale'):
        scale = line.split()[-1]
        d[ind][sub_ind].append(scale)

    if line.startswith('Description'):
        desc = line.split(': ')[-1].replace('\n', '')
        d[ind][sub_ind].append(desc)

输出:

{
    '1': {
        '0': ['Name of Object 1', 'Q0', 'Object 1 does this']
        },
    '2': {
        '0': ['Object 2 yo', 'Q0', 'Something important'],
        '1': ['Object 2 yo', '0.125', 'Object 2 does that']
        }
}