为循环performan嵌套的Elementtree

2024-06-30 08:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xml,格式如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<decodedData fileName="/home/awips/Downloads/20190726_1600" storageType="mesonet" type="MISC" root="MISC" source="MADIS" provider="MADIS" missingValue="-9999" reportTime="1564156800">
<field variableName="providerId" units="STRING" type="STRING">
  <v>EW2304</v><v>EW9455</v><v>KSC08</v> #<--potentially a lot of these variables
</field>
<field variableName="stationName" units="STRING" type="STRING">
  <v>EW2304 Melbourne.CB                  FL US</v><v>EW9455 Melbourne                  FL US</v><v>KSC714 - Merritt Isl Wildlife Re FL US</v>
</field>
<field variableName="observationTime" units="DATE_TIME_STRING" type="DATE_TIME">
  <v>2019/07/26 16:00:12</v><v>2019/07/26 16:00:15</v><v>2019/07/26 16:00:00</v>
</field>
</decodedData>

我尝试将<v> and </v>之间的值放入它们各自的列表中,在非常大的文件上具有更好的性能。你知道吗

以下是我尝试的:

#!/bin/python
from xml.etree import ElementTree

tree = ElementTree.parse("test7.txt")
providerId,stationName,observationTime = ([] for i in range(3))

for m in olp:
        for n in m:
                if ("providerId" in m.attrib.values()): 
                       providerId.append(n)
                if ("stationName" in m.attrib.values()): 
                       stationName.append(n)
                if ("observationTime" in m.attrib.values()): 
                       observationTime.append(n)

#real    1m17.215s
#user    1m15.686s
#sys     0m1.524s

我也试过:

olp = tree.find('.//field[@variableName="providerId"]')
providerId = list(olp.iter("v"))
olp = tree.find('.//field[@variableName="stationName"]')
stationName = list(olp.iter("v"))
olp = tree.find('.//field[@variableName="observationTime"]')
observationTime = list(olp.iter("v"))

#real    1m23.255s
#user    1m21.606s
#sys     0m1.644s

我也有另一个想法,但我不知道该怎么写,所以不确定性能这里有一些伪代码,将整行作为一个字符串,然后将整个字符串拆分为一个巨大的列表:

string = ElementTree.tostring(tree.find('.//field[@variableName="providerId"]'))
[code here to split between >< brackets into a list keeping delimiter]

当给定非常大的文件时,两者似乎都不能提供性能。最好的方法是什么?你知道吗


Tags: intreefieldstringtypexmlfindlist