1

我有一些看起来像 YAML 的数据,但不是。这是一个例子;

An instance of A
  objectID=123
  family=abc

An instance of A
  objectID=234
  family=bcd
  List of 4 X elements:
    An instance of X:
      objectID=222
      name=ccc
    An instance of X:
      objectID=333

等等...

我需要找到一种方法让它看起来更像这样:

[
  {'name': 'An instance of A',
   'data': [
     {'objectID': 123,
      'family': 'abc'
     }
   ]
 },
 ...

我试图创建一些递归函数来解析它,但它最终变得一团糟。

我不是要一个完整的工作示例,但是在 python 中执行此操作的最佳方法是什么?自调用功能?使用另一个库(我还没有找到)?使用另一种语言来帮助我并将整个东西嵌入到 python 中?

4

1 回答 1

3

使用堆栈,并在发现更多或更少的缩进级别时从中推送和弹出项目;堆栈上的每一层都包含缩进深度和条目:

stack = [(0, {})]  # indentation level, top-level entry
entry = stack[-1][1]

for line in input:
    line = line.strip()
    if not line: continue

    indentation = len(input) - len(input.lstrip())
    if indentation > stack[-1][0]:  # indented further? New entry
        entry = stack[-1][1]['data'] = {}
        stack.append((indentation, entry)) # push
    else:
        while indentation < stack[-1][0]:  # indentation dropped
            del stack[-1]       # pop
            entry = stack[-1][1]

    # process line and add to entry

result = stack[0][1]
于 2012-11-26T11:47:26.220 回答