아마도 뭔가를 간과 할 것이지만 "getAllElements"함수를 사용하여 "parse"클래스를 얻었습니다. 주요 스크립트에서 나는 그럼 잘 작동NameError : 클래스 함수를 호출 할 때 전역 이름 'getAllElements'가 정의되어 있지 않습니다.
parse = parse(file)
을
from parseXML import parse.
를 사용하여 구문 분석 가져옵니다. 내가
print parseXML.parse(file).getAllElements()
을 할 때 나는 다음과 같은 오류가 발생합니다 :
NameError: global name 'getAllElements' is not defined
아래는 코드입니다. 내가 어디로 잘못 가고 있니?
편집 : 코멘트
class parse:
# Constructor
def __init__(self, file):
# parse the xml file into a tree
tree = xml.parse('/homes/ndeklein/test.featureXML')
# Get the root node of the xml file
self.rootElement = tree.getroot()
# Set self.parent to rootElement, because the first element won't have a parent (because it is the root)
self.parent = 'rootElement'
# dictionary that contains the parent -> child relation
self.parentChildDict = {}
# Go recursively through all the elements in the xml file, starting at the choosen rootElement, until only leaves (elements that don't contain elements) are left
# Return all the elements from the xml file
def getAllElements(self):
# if this is the first time this parent is seen:
# make elementDict with parent as key and child as value in a list
if not self.parentChildDict.has_key(self.parent):
self.parentChildDict[self.parent] = [self.rootElement]
# else: add the child to the parent dictionary
else:
self.parentChildDict[self.parent].append(self.rootElement)
for node in self.rootElement:
# if the len of rootElement > 0 (there are more elements in the element):
# set self.parent to be node and recursively call getAllElements
if len(self.rootElement) > 0:
self.parent = node
getAllElements()
return self.parentChildDict
후 코드를 변경했습니다. parseXML
로컬 네임 스페이스에없는 것처럼 당신이 from parseXML import parse
을하고 있기 때문에
#!/usr/bin/env python
# author: ndeklein
# date: 08/02/2012
# function: calls out the script
import parseXML
import xml.etree.cElementTree as xml
import sys
#Parse XML directly from the file path
file = '/homes/ndeklein/EP-B1.featureXML'
# parse the xml file into a tree
print parseXML.parse(file).getAllElements()
코드를 빠르게 보면 여러 가지 문제가 있습니다 ... 처음에는 t 그는'class' 정의 문법이 정확하지 않습니다.'getAllElements'는 문법 오류 ('self.parent' 대신'parent')를 가지고 있습니다. 코드를 수정하고 수정하고 적절한 수입으로 다시 시도하십시오. –
감사합니다. 클래스 정의를 변경하고 사용하지 않는 부분을 제거하고 찾을 수있는 모든 구문 오류를 가져 왔지만 여전히 동일한 오류가 발생합니다. –
아니요, 코드에는 여전히 문제가 있습니다. 끝에서 두 번째 줄에서'getAllElements()'를 자세히 살펴보십시오. 그게 너처럼 보이니? 'self.getAllElements()'가 필요합니다. 이것은 당신의 이름 오류의 원인이되는 것입니다. 그러나 코드에는 여전히 논리적 오류가 있습니다.반환 값으로 무엇을하고 있습니까? 그냥 버리는거야. –