저는 파이썬에 익숙하지 않으며 텍스트 파일에서 입력을 가져온 후에 파이썬으로 트리를 빌드해야합니다.
텍스트 파일에 아래 데이터가 있습니다. 나는 아래의 데이터가 내가 아래의 코드를 작성 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
제가 보는 오류가 JSON과 관련된 디코딩 오류입니다 (당신이 마지막 줄에 초에 닫는 대괄호 누락 된 것 같습니다) –
그리고 buildnode 메소드를 호출하기 위해 그것의 인스턴스를 호출하지 않고 클래스를 사용한다 –