【发布时间】:2021-05-18 14:57:36
【问题描述】:
我正在尝试将缩进文本转换为 python 中的嵌套字典列表 受此线程的启发 Creating a tree/deeply nested dict from an indented text file in python 它帮助我开始,但我仍然未能达到预期的结果
indented_text = """
# Level 1
## Level 2
### Level 3
#### Level 4
##### Level 5
###### Level 6
##### Level 5
#### Level 4
##### Level 5
###### Level 6
### Level 3
#### Level 4
## Level 2
### Level 3
#### Level 4
#### Level 4
### Level 3
"""
class Node:
def __init__(self, indented_line):
# self.t = t
# self.d = d
# self.p = {}
# self.v = v ---------
# self.c = [] ------
self.t = 'list_item'
self.d = indented_line.index('# ') # len(indented_line) - len(indented_line.lstrip())
self.p = {}
self.v = indented_line[self.d + 1:].strip()
self.c = []
def add_children(self, nodes):
childlevel = nodes[0].d
while nodes:
node = nodes.pop(0)
if node.d == childlevel: # add node as a child
self.c.append(node)
elif node.d > childlevel: # add nodes as grandchildren of the last child
nodes.insert(0,node)
self.c[-1].add_children(nodes)
elif node.d <= self.d: # this node is a sibling, no more children
nodes.insert(0,node)
return
root = Node('# root')
root.add_children([Node(line) for line in indented_text.splitlines() if line.strip()])
现在我需要输出
{
"t": "heading",
"d": 1,
"p": {},
"v": "Level 1",
"c": [
{
"t": "heading",
"d": 2,
"p": {},
"v": "Level 2",
"c": [
{
"t": "heading",
"d": 3,
"p": {},
"v": "Level 3",
"c": [
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4",
"c": [
{
"t": "heading",
"d": 5,
"p": {},
"v": "Level 5",
"c": [
{
"t": "heading",
"d": 6,
"p": {},
"v": "Level 6"
}
]
},
{
"t": "heading",
"d": 5,
"p": {},
"v": "Level 5"
}
]
},
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4",
"c": [
{
"t": "heading",
"d": 5,
"p": {},
"v": "Level 5",
"c": [
{
"t": "heading",
"d": 6,
"p": {},
"v": "Level 6"
}
]
}
]
}
]
},
{
"t": "heading",
"d": 3,
"p": {},
"v": "Level 3",
"c": [
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4"
}
]
}
]
},
{
"t": "heading",
"d": 2,
"p": {},
"v": "Level 2",
"c": [
{
"t": "heading",
"d": 3,
"p": {},
"v": "Level 3",
"c": [
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4"
},
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4"
}
]
},
{
"t": "heading",
"d": 3,
"p": {},
"v": "Level 3"
}
]
}
]
}
我无法完成并获得所需的输出...
【问题讨论】:
-
你得到什么输出?它与您的预期有何不同?您尝试过什么调试来解决问题?你能把你的代码压缩成一个minimal reproducible example 并格式化你的预期输出以便它可读吗?
-
为什么/你添加的那些手册 c、v、t、d、p 是什么?
-
@PranavHosangadi 输出是我的问题我不知道如何将其转换为可打印的 dict / json 字符串
-
@TenaciousB 我不确定你的意思,这是我需要输出的格式
标签: python json dictionary parsing