在使用此处提供的以下代码期间,我会出现语法错误,我不知道为什么!我猜这是因为我没有在代码中安装提到的库,但事实并非如此。
import os
import xml.etree.ElementTree as ET
#A helpful function to load compressed or uncompressed XML files
def loadXMLFile("config.xml"):
#Check if the file is compressed or not, and
if (os.path.splitext("config.xml")[1][1:].strip() == "bz2"):
import bz2
f = bz2.BZ2File("output.bz2")
doc = ET.parse(f)
f.close()
return doc
else:
return ET.parse("config.xml")
#Load the XML file config.out.xml
XMLDoc=loadXMLFile("config.out.xml")
#We can create a list of all particle tags using an xpath expression
#(xpath expressions always return lists)
PtTags = XMLDoc.findall("//Pt")
#Print the number of particles
print len(PtTags)
#print the x, y, and z positions of each particle
for PtElement in PtTags:
PosTag = PtElement.find("P")
print PosTag.get("x"), PosTag.get("y"), PosTag.get("z"), PtElement.get("D")
这是其中有“文件名”的原始文件
#!/usr/bin/python
import os
import xml.etree.ElementTree as ET
#A helpful function to load compressed or uncompressed XML files
def loadXMLFile(filename):
#Check if the file is compressed or not, and
if (os.path.splitext(filename)[1][1:].strip() == "bz2"):
import bz2
f = bz2.BZ2File(filename)
doc = ET.parse(f)
f.close()
return doc
else:
return ET.parse(filename)
#Load the XML file config.out.xml
XMLDoc=loadXMLFile("config.out.xml")
#We can create a list of all particle tags using an xpath expression
#(xpath expressions always return lists)
PtTags = XMLDoc.findall("//Pt")
#Print the number of particles
print len(PtTags)
#print the x, y, and z positions of each particle
for PtElement in PtTags:
PosTag = PtElement.find("P")
print PosTag.get("x"), PosTag.get("y"), PosTag.get("z"), PtElement.get("D")
我不知道我面临这个错误的错误是什么?目录有错误吗?或者文件名可能有一些问题?