簡體   English   中英

將多行字符串轉換為Dict-Python

[英]Convert Multiline String to Dict - Python

我有一個多行字符串,我想轉換成Dict。 多行字符串看起來像

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

我做到了

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

以下我嘗試將“文本”轉換為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)

但是當我運行這段代碼時,我得到的輸出如下:

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

預期結果應為:

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

誰能幫我這個 ...

更改

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

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

您還可以編寫解析邏輯,如下所示:

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