2013-03-04 2 views
5

저는 파이썬에 익숙하지 않으며 텍스트 파일에서 입력을 가져온 후에 파이썬으로 트리를 빌드해야합니다.
텍스트 파일에 아래 데이터가 있습니다. 나는 아래의 데이터가 내가 아래의 코드를 작성 json 객체를 가져 와서 재귀를 통해 파이썬에서 트리를 빌드하십시오.

  { 
       "component": "A", 
       "status": 0, 
       "children": [ 
        { 
         "component": "AA", 
         "status": 0, 
         "children": [ 
          { 
           "component": "AAA", 
           "status": 0, 
           "children": [] 
          }, 
          { 
           "component": "AAB", 
           "status": 0, 
           "children": [] 
          } 
         ] 
        }, 
        { 
         "component": "AB", 
         "status": 0, 
         "children": [ 
          { 
           "component": "ABA", 
           "status": 0, 
           "children": [] 
          }, 
          { 
           "component": "ABB", 
           "status": 0, 
           "children": [] 
          } 
         ] 
        } 
      } 

JSON

을 사용하여 파이썬에서 나무를 구축해야하지만, 하나라도 찾아 낼 수있는 경우에없는 임 수정하는 구문 오류가 그들

  class node: 
       #Construction of Node with component,status and children 
       def _init_(self,component=None,status=None,children=None): 
        self.component = component 
        self.status = status 
        if children is None: 
         self.children = [] 
        else: 
         self.children = children 

      #Building Json object from text file    
      class start: 
       import json 

       f=open("json_file.txt") 
       data=json.load(f) 
       buildnode(data) 


      #Construction of tree through recursion    
      class implementation: 
       def buildnode(self,ob): 
        node1= node() 
        node1.component=ob.component 
        node1.status=ob.status 
        node1.children=[] 
        print 'component',component,'','status',status 
        for children in ob: 
         node1.children.add(buildnode(children[i])) 

        return node1 
+0

제가 보는 오류가 JSON과 관련된 디코딩 오류입니다 (당신이 마지막 줄에 초에 닫는 대괄호 누락 된 것 같습니다) –

+1

그리고 buildnode 메소드를 호출하기 위해 그것의 인스턴스를 호출하지 않고 클래스를 사용한다 –

답변

1

확인 난 당신의 코드에서 버그를 수정 할 수 있었다 지금은 다음과 같습니다

class node: 
    #Construction of Node with component,status and children 
    def _init_(self,component=None,status=None,children=None): 
     self.component = component 
     self.status = status 
     if children is None: 
      self.children = [] 
     else: 
      self.children = children 

#Construction of tree through recursion    
class implementation: 
    def buildnode(self,ob): 
     node1= node() 
     node1.component=ob['component'] 
     node1.status=ob['status'] 
     node1.children=[] 
     print 'component',node1.component,'','status',node1.status 
     for children in ob['children']: 
      node1.children.append(self.buildnode(children)) 

     return node1 

#Building Json object from text file    
class start: 
    import json 

    f=open("json_file.txt") 
    data=json.load(f) 
    builder = implementation() 
    builder.buildnode(data) 

이 다음과 같은 출력이 생성

,691을 여기
component A status 0 
component AA status 0 
component AAA status 0 
component AAB status 0 
component AB status 0 
component ABA status 0 
component ABB status 0 

필요한 있었는지에 대한 몇 가지 설명입니다

먼저 호출하는 당신의 buildnode() 당신이 그것을 정의하기 전에, 당신이 그것을 호출하기 전에 클래스의 인스턴스를 필요 그래서 클래스 함수이다. 다음으로 사전에 값을 호출 할 때는 dictionary['key']에 액세스해야합니다. 배열에 추가하는 유일한 방법은 .append()이고 .add()이 아니라는 것입니다.

+0

왜 downvote인가? –

+0

Jason에게 감사드립니다. 그것이 실제로 효과가 있었는지 믿을 수 없다. 심지어 나의 멘토도 잡을 수없는 모든 문제를 해결했다 ... 감사 : D – Praneeth

+0

멘토가이 답변에 투표를했다 : P 다행스럽게도 나는 파이썬을 배우는 것을 즐기고있다. 잘 –

4
import json 

class Node(object): 
    def __init__(self, component=None, status=None, level=0): 
     self.component = component 
     self.status = status 
     self.level  = level 
     self.children = [] 

    def __repr__(self):   
     return '\n{indent}Node({component},{status},{children})'.format(
             indent = self.level*'\t', 
             component = self.component, 
             status = self.status, 
             children = repr(self.children)) 
    def add_child(self, child): 
     self.children.append(child)  

def tree_builder(obj, level=0): 
    node = Node(component=obj['component'], status=obj['status'], level=level) 
    for child in obj.get('children',[]): 
     node.add_child(tree_builder(child, level=level+1)) 
    return node 

def load_json(filename): 
    with open(filename) as f: 
     return json.load(f) 

obj = load_json('test.json') 
tree = tree_builder(obj) 
print tree 

출력 :

Node(A,0,[ 
    Node(AA,0,[ 
     Node(AAA,0,[]), 
     Node(AAB,0,[])]), 
    Node(AB,0,[ 
     Node(ABA,0,[]), 
     Node(ABB,0,[])])]) 
+0

+1 거기에 깊이 코드를 가져오고 깨끗한 클래스 디자인을 위해서 –

+0

나의 멘토는 이것을 보니 정말 기쁘다 .... 나는 내가 이걸 독자적으로 쓴다고 말했다. P 감사합니다. – Praneeth

관련 문제