2013-03-04 11 views
5

Jestem nowy w python i muszę zbudować drzewo w pytonie po pobraniu z pliku tekstowego
Mam poniższe dane w pliku tekstowym. Muszę zbudować drzewo w Pythonie z poniższym danych za pomocą JSONZbuduj drzewo w pythonie przez rekurencję przez wzięcie obiektu 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": [] 
          } 
         ] 
        } 
      } 

napisałem poniższy kod, ale zawiera błędy składniowe, które Im stanie poprawne, jeśli ktoś może je znaleźć

  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

Błąd widzę jest błąd związany z dekodowania JSON (wygląda na to, że brakuje zamykający nawias kwadratowy na przedostatniej linii) –

+1

A użycie klasy bez wywoływania jej wystąpienia w celu wywołania jej metody buildnode. –

Odpowiedz

1

Ok udało mi się naprawić błędy w kodzie i teraz wygląda to tak:

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) 

to daje następujący wynik:

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 

Oto wyjaśnienie, co było potrzebne:

Najpierw dzwonisz Twój buildnode() zanim ją zdefiniować, a to jest funkcją klasy więc trzeba instancję klasy przed nazwać. Następnie, gdy wywołujesz wartości w słowniku, musisz uzyskać do nich dostęp pod numerem dictionary['key']. Jedyną ważną rzeczą było dodanie do tablicy: .append(), a nie .add().

+0

Dlaczego w dół? –

+0

Wielkie dzięki Jason. Nie mogę uwierzyć, że to zadziałało, rozwiązałeś wszystkie problemy, których nawet mój mentor nie mógł złapać ... dzięki: D – Praneeth

+0

Czy twój mentor głosował na tę odpowiedź: P Cieszę się, że mogłem pomóc :) Cieszę się uczeniem się Pythona jako dobrze –

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 

wyjściowa:

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

+1 za uzyskanie kodu głębokości tam i czystszego projektu klasy –

+0

Mój mentor jest naprawdę zadowolony widząc to .... Powiedziałem mu, że napisałem to na własną rękę: P dzięki – Praneeth

Powiązane problemy