Skip to main content
 首页 » 编程设计

Python递归函数调用次数过多

2024年10月01日6tuyile006

这是这个问题的后续:Python parse text file into nested dictionaries

我最初接受了建议使用正则表达式格式化输入的答案,但在仔细查看输入后,仍然存在一些我无法使用建议的正则表达式处理的问题。

所以我又回到了递归地将这些行解析到字典中。

我目前拥有的是:

def parseToDictionary(input): 
    key = '' 
    value = '' 
    result = {} 
 
    if input[0].startswith('{'): # remove { 
        del input[0] 
 
    result.clear() # clear the dict for each recursion 
 
    for idx, line in enumerate(input): 
        line = line.rstrip() # remove trailing returns 
 
        if line.startswith('['): 
            key = line 
            value = parseToDictionary(input[idx+1:]) # parse the next level 
        elif line.startswith('}'): # reached the end of a block 
            return result 
        else: 
            elements = line.split('\t') 
            key = elements[0] 
            if len(elements) > 1: 
                value = elements[1] 
            else: 
                value = 'Not defined' # some keys may not have a value, so set a generic value here 
        if key: 
            result[key] = value 
 
    return result 

这是一个示例(非常简单!)输入:

[HEADER1] 
{ 
key1    value 
key2    long value, with a comma 
[HEADER2] 
{ 
key 1234 
emptykey 
} 
} 

输出是:

'[HEADER2]':  
{ 
    'emptykey': 'Not defined',  
    'key': '1234' 
},  
'key2': 'long value, with a comma',  
'key1': 'value',  
'[HEADER1]':  
{ 
    'emptykey': 'Not defined',  
    'key2': 'long value, with a comma',  
    'key1': 'value',  
    'key': '1234',  
    '[HEADER2]':  
    { 
        'emptykey': 'Not defined',  
        'key': '1234' 
    } 
 },  
 'emptykey': 'Not defined',  
 'key': '1234' 
 } 

但应该是:

'[HEADER1]':  
{ 
    'key1': 'value',  
    'key2': 'long value, with a comma',  
    '[HEADER2]':  
    { 
        'emptykey': 'Not defined',  
        'key': '1234' 
    } 
 } 

所以以 [ 开头的每一行都是下一个 block 的键。每个 block 内有多个键值对,也可以有另一个嵌套级别。问题是某些 block 被解析了多次,我无法弄清楚哪里出了问题。

入参为mydatafile.split('\n')

谁能帮帮我?

请您参考如下方法:

您必须跳过在小节中处理的行:

def parse_to_dictionary(lines): 
    def parse_block(lines): 
        contents = {} 
        if next(lines).strip() != '{': 
            raise AssertionError("'{' expected") 
        for line in lines: 
            line = line.strip() 
            if line == '}': 
                return contents 
            elif line[0] == '[': 
                contents[line] = parse_block(lines) 
            else: 
                parts = line.split('\t', 1) 
                contents[parts[0]] = None if len(parts) == 1 else parts[1] 
 
    lines = iter(lines) 
    key = next(lines)                 
    if key[0] != '[': 
        raise AssertionError("format error") 
    return {key: parse_block(lines)}