Python 从标识符构建json树结构
我有一个包含如下数据的文件:Python 从标识符构建json树结构,python,json,tree,identifier,Python,Json,Tree,Identifier,我有一个包含如下数据的文件: ID attribute 1 'text' 101 'text' 1011 'text' 10111 'text' 1011101 'text' 1011102 'text' 1011103 'text' 1011104 'text' 1011130 'text' [ {'id': ID, 'attr' : text}, {...} ] 我的目标是从以下数据构建json树结构: { [ ID : 1, attribute : 'text'
ID attribute
1 'text'
101 'text'
1011 'text'
10111 'text'
1011101 'text'
1011102 'text'
1011103 'text'
1011104 'text'
1011130 'text'
[ {'id': ID, 'attr' : text}, {...} ]
我的目标是从以下数据构建json树结构:
{
[
ID : 1,
attribute : 'text',
children : [
ID: 101,
attribute : 'text',
children : [
...
ID : 2,
...
]
}
在python中,我构建了一个词汇表,如下所示:
ID attribute
1 'text'
101 'text'
1011 'text'
10111 'text'
1011101 'text'
1011102 'text'
1011103 'text'
1011104 'text'
1011130 'text'
[ {'id': ID, 'attr' : text}, {...} ]
我想我可以利用leaf id包含他父母id的事实,但我看不到构建我想要的结构的方法
如果您能在伪代码或任何其他编程语言方面提供帮助,我将不胜感激。我不太了解您的ID编号系统,因此下面是一个简单前缀树的代码:
ls = """
1 'text'
101 'text'
1011 'text'
10111 'text'
1011101 'text'
2 two
2111 'text'
21114 'text'
25 'text'
2567 'text'
"""
ls = map(str.split, ls.strip().splitlines())
tree = [{'prefix': '', 'children':[]}]
stack = [tree[0]]
for id, attr in ls:
while not id.startswith(stack[-1]['prefix']):
stack.pop()
node = {'prefix': id, 'attr': attr, 'children': []}
stack[-1]['children'].append(node)
stack.append(node)
import pprint
pprint.pprint( tree)
thg435的解决方案几乎没有变化:
# open & read raw file
f=open(args[0], 'r')
text = f.read()
#
text = map(lambda s: s.split(" ", 1), text.strip().replace("'","").splitlines())
tree = [{'prefix': '', 'children':[]}]
stack = [tree[0]]
for id, attr in text:
while not id.startswith(stack[-1]['prefix']):
stack.pop()
node = {'prefix': id, 'attr': attr, 'children': []}
stack[-1]['children'].append(node)
stack.append(node)
pprint.pprint( tree)
print json.dumps( tree)
f=open(args[1], 'w')
f.write(json.dumps( tree, sort_keys=True, indent=1))
谢谢 我想如果有超过99棵顶级树的话,不管怎样,使用这种格式,你都会遇到麻烦。