我试图只计算代码属性大于或等于10的文件标记。下面是我的代码:-在
from xml.dom.minidom import parse, parseString
import xml.dom.minidom
DOMTree = xml.dom.minidom.parse("param.xml")
group = DOMTree.documentElement
code_line_10=[0,1,2,3,4,5,6,7,8,9]
num_source_file = 0
for file in group.getElementsByTagName("file"):
if file.hasAttribute("code"):
attribute_value = file.getAttribute("code")
if attribute_value not in code_line:
num_source_file += 1
print(num_source_file)
这是我使用:-在
^{pr2}$在执行上述代码时,它将计算xml文档中的所有文件标记,包括我要排除的那些。我在做什么我做的不对?在
getAttribute以字符串形式返回值。尝试类似于:
使用支持xpath的库,如lxml,然后可以执行以下操作:
file.getAttribute("code")
返回str
对象,'1' in [1]
是False
。现在有多种方法可以解决你的问题。在首先是坏的解决方案:
code_line_10=[0,1,..,9]
替换为code_line_10=['0','1',..,'9']
。在if attribute_value not in code_line:
更改为if int(attribute_value) not in code_line:
(注意,如果代码属性不能转换为int,则会引发异常)在这两种解决方案中,算法仍然需要遍历列表中的所有项目,并逐个比较这些项目,这需要一些时间。更快的解决方案是将值与运算符
<=
进行比较。因此可以将if替换为if int(attribute_value) >= 10:
(同样,如果代码属性不能转换为int,则会引发异常)相关问题 更多 >
编程相关推荐