Python 递归函数调用次数过多

标签 python parsing dictionary nested

这是此问题的后续内容: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)}

关于Python 递归函数调用次数过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46994348/

相关文章:

python - 64位Oracle客户端库无法在mac中加载

Python 对 groupby 求和两次

python - 在 Python 中,将由关键字对组成的列表添加到字典中最简单的方法是什么?

java - 如何将多行文件变成用控制字符分隔的单行文件

JavaScript 伪字典

Python:字典的分组和聚合列表[不带计数器]

python - 在 python 中查找所有窗口的 exe 路径

python - 无法使用 ZipFile 打开子目录中的文件

javascript - 解析 neo4j JSON 响应

python - 使用 isdigit 进行 float ?