2013-03-04 61 views
5

Tôi mới dùng python và tôi phải xây dựng một cây trong python sau khi nhập vào từ một tệp văn bản
tôi có dữ liệu bên dưới trong tệp văn bản. Tôi có để xây dựng một cây trong python với các dữ liệu dưới đây sử dụng JsonTạo một cây trong python thông qua đệ quy bằng cách lấy đối tượng 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": [] 
          } 
         ] 
        } 
      } 

tôi đã viết code dưới đây nhưng nó có lỗi cú pháp mà Im không thể sửa nếu có ai có thể tìm thấy chúng

  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

Các lỗi tôi nhìn thấy là một lỗi giải mã liên quan đến JSON (có vẻ như bạn đang thiếu một khung vuông đóng cửa ngày thứ hai đến dòng cuối cùng) –

+1

Và sử dụng một lớp mà không cần gọi một thể hiện của nó để gọi nó là phương thức buildnode –

Trả lời

1

Ok tôi đã có thể sửa chữa các lỗi trong mã của bạn và bây giờ nó trông như thế này:

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) 

này tạo ra kết quả như sau:

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 

Dưới đây là một số giải thích cho những gì là cần thiết:

Trước tiên, bạn đang kêu gọi buildnode của bạn() trước khi bạn định nghĩa nó, và nó là một chức năng lớp vì vậy bạn cần một thể hiện của lớp trước khi bạn gọi nó. Tiếp theo khi bạn đang gọi cho các giá trị bên trong một từ điển bạn cần truy cập chúng bằng dictionary['key']. Điều lớn khác duy nhất là cách để gắn thêm vào một mảng là gọi .append() và không phải .add().

+0

Tại sao downvote? –

+0

Cảm ơn rất nhiều Jason. Không thể tin rằng nó thực sự làm việc, u giải quyết tất cả các vấn đề mà ngay cả cố vấn của tôi không thể bắt ... cảm ơn: D – Praneeth

+0

Là cố vấn của bạn bỏ phiếu cho câu trả lời này: P Vui mừng tôi có thể giúp :) Tôi thích học Python như Vâng –

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 

Output:

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

+1 để lấy mã độ sâu trong đó và thiết kế lớp học sạch hơn –

+0

Người cố vấn của tôi thực sự hài lòng khi thấy điều này .... tôi đã nói với anh ấy tôi đã viết điều này một mình: P cảm ơn – Praneeth

Các vấn đề liên quan