2013-03-04 10 views
5

Sono nuovo in Python e devo costruire un albero in python dopo aver preso in input da un file di testo
ho i seguenti dati in un file di testo. Devo costruire un albero in pitone con i dati di seguito utilizzando JSONCostruisci un albero in python attraverso la ricorsione prendendo in oggetto 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": [] 
          } 
         ] 
        } 
      } 

ho scritto il codice qui sotto, ma ha gli errori di sintassi che Im in grado di correggere se qualcuno riesce a trovare loro

  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

L'errore che sto vedendo è un errore di decodifica relativo al JSON (sembra che vi manca una parentesi quadra di chiusura sulla penultima riga) –

+1

E il uso di una classe senza invocare un'istanza per richiamare il suo metodo buildnode –

risposta

1

Ok sono stato in grado di risolvere i bug nel codice e ora sembra che questo:

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) 

questo produce il seguente output:

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 

Ecco qualche spiegazione per ciò che era necessario:

In primo luogo si sta chiamando il vostro buildnode() prima di definire esso, ed è una funzione di classe quindi è necessario un'istanza della classe prima di chiamare esso. Successivamente, quando si richiedono valori all'interno di un dizionario, è necessario accedervi tramite dictionary['key']. L'unica altra grande cosa era il modo per aggiungere a un array è chiamare .append() e non .add().

+0

Perché il downvote? –

+0

Grazie mille Jason. Non posso credere che abbia funzionato davvero, hai risolto tutti i problemi che anche il mio mentore non riusciva a cogliere ... grazie: D – Praneeth

+0

Il tuo mentore ha votato su questa risposta: P Felice di poter aiutare :) Mi sto divertendo a imparare Python come bene –

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 

uscita:

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

+1 per ottenere il codice di profondità e un design di classe più pulito –

+0

Il mio mentore è davvero contento di vedere questo .... Gli ho detto che l'ho scritto da solo: P grazie – Praneeth

Problemi correlati