2012-06-10 6 views
1

에서 JSON 트리 구조를 구축 내가 그렇게 보이는 데이터 파일이 있습니다식별자

ID attribute 
1 'text' 
101 'text' 
1011 'text' 
10111 'text' 
1011101 'text' 
1011102 'text' 
1011103 'text' 
1011104 'text' 
1011130 'text' 

내 목표는 이러한 데이터에서 JSON 트리 구조를 구축하는 것입니다 : 파이썬에서

{ 
    [ 
    ID : 1, 
    attribute : 'text', 
    children : [ 
     ID: 101, 
     attribute : 'text', 
     children : [ 
      ... 
    ID : 2, 
     ... 
    ] 
} 

, 나는 그런 사전의 목록을 만들었다 :

[ {'id': ID, 'attr' : text}, {...} ] 

나는 잎 ID가 그의 부모를 포함한다는 사실을 사용할 수 있다고 생각한다. id하지만 내가 원하는 구조를 만드는 방법을 볼 수 없습니다.

의사 코드 나 기타 프로그래밍 언어로 도움을 받으실 수 있습니다.

+0

어쨌든 그 상위 99 개 트리가 더 있으면 문제가 생길 것입니다. – TankorSmash

답변

0

솔루션은 작은 변화 일 :

# 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)) 

감사합니다!

3

나는 확실히 당신의 ID 번호 시스템을 얻을, 그래서 여기에 간단한 접두사 트리 코드의 한 : thg435에서

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) 
+0

+1. 거기에 대한 설명을 던지면 스튜가 생깁니다. – TankorSmash