我有一个文本文件的例子:(我不知道你叫什么,一棵树?)
key1
subkey1
subkey2
choice1
key2
subkey1
subkey2
我希望它看起来像这样:
[
{
"text":"key1",
"children":[
{
"text":"subkey1",
children:[]
},
{
"text":"subkey2",
children:[
{
"text":"choice1",
"children":[]
}
]
},
]
},
{
"text":"key2",
"children":[
{
"text":"subkey1",
children:[]
},
{
"text":"subkey2",
children:[]
},
]
}
]
这就是我正在做的事情,我不明白你如何将子元素带入父元素,这应该能够无限深入。
import itertools
def r(f, depth, parent, l, children):
for line in f:
line = line.rstrip()
newDepth = sum(1 for i in itertools.takewhile(lambda c: c=='\t', line))
node = line.strip()
if parent is not None:
print parent, children
children = [{"txt":node, "children":[]}]
# l.append({"txt":parent, "children":children})
r(f, newDepth, node, l, children)
json_list = []
r(open("test.txt"), 0, None, json_list, [])
print json_list
答案 0 :(得分:5)
第一条规则,如果可以,请避免递归......在这里,您只需要知道祖先,并且可以轻松地将它们保存在列表中。请注意,depth
0是为根节点保留的,第一个“用户”深度为1
,因此在计算选项卡时为+1
。
f = open("/tmp/test.txt", "r")
depth = 0
root = { "txt": "root", "children": [] }
parents = []
node = root
for line in f:
line = line.rstrip()
newDepth = len(line) - len(line.lstrip("\t")) + 1
print newDepth, line
# if the new depth is shallower than previous, we need to remove items from the list
if newDepth < depth:
parents = parents[:newDepth]
# if the new depth is deeper, we need to add our previous node
elif newDepth == depth + 1:
parents.append(node)
# levels skipped, not possible
elif newDepth > depth + 1:
raise Exception("Invalid file")
depth = newDepth
# create the new node
node = {"txt": line.strip(), "children":[]}
# add the new node into its parent's children
parents[-1]["children"].append(node)
json_list = root["children"]
print json_list