简体   繁体   English

将多行字符串转换为Dict-Python

[英]Convert Multiline String to Dict - Python

I have a multiline string, and I want to convert into Dict. 我有一个多行字符串,我想转换成Dict。 the multiline string seems like 多行字符串看起来像

text='''
     one:
        two:
            three
            four
        five:
            six
            seven
     '''

And i did, 我做到了

result={}
step1=step2=step3=''
lines=text.split('\n')

the following code that I tried to convert that 'text' to Dict 以下我尝试将“文本”转换为Dict的代码

for line in lines:
    if re.search(r'^(\w+):$',line,re.M):
        out=re.search(r'^(\w+):$',line,re.M)
        step1=out.group(1)
        result[step1]={}
    if re.search(r'^\s{4}(\w+):$',line,re.M):
        out=re.search(r'^\s{4}(\w+):$',line,re.M)
        step2=out.group(1)
        result[step1][step2]={}
    if re.search(r'^\s{8}(\w+)$',line,re.M):
        out=re.search(r'^\s{8}(\w+)$',line,re.M)
        item1=out.group(1)
        result[step1][step2]=[]
        result[step1][step2].append(item1)

print(result)

But when I ran this code I'm getting output like: 但是当我运行这段代码时,我得到的输出如下:

{'one': {'two': ['four'], 'five': ['seven']}}

And the Expected result should be: 预期结果应为:

{'one': {'two': ['three','four'], 'five': ['six','seven']}}

Can anyone help me with this ... 谁能帮我这个 ...

Change 更改

result[step1][step2]=[]
result[step1][step2].append(item1)

To

if not result[step1][step2]:
    result[step1][step2]=[item1]
else:
    result[step1][step2].append(item1)

Also you can write your parse logic as follows: 您还可以编写解析逻辑,如下所示:

for line in lines:
    out = re.search(r'^(\w+):$',line,re.M)
    if out:
        step1 = out.group(1)
        result[step1] = {}
        continue
    out = re.search(r'^\s{4}(\w+):$',line,re.M)
    if out:
        step2 = out.group(1)
        result[step1][step2] = []
        continue
    out = re.search(r'^\s{8}(\w+)$',line,re.M)
    if out:
        item = out.group(1)
        result[step1][step2].append(item)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM