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