我有一个 XML 文件,我需要从中提取 ID 和标题字段(在页面标记下)。这就是我正在做的,而且效果很好。但是,我对 elem.find('title) 的三个调用不满意。有没有更好的方法可以通过理解来避免这种情况?我明白写一个循环可以解决这个问题。
import xml.etree.ElementTree as ET
tree = ET.parse(some file)
root = tree.getroot()
id_title_list = [(elem.find('id').text, elem.find('title').text)
for elem in root.findall('page')
if elem.find('title').text.startswith('string1') or
elem.find('title').text.startswith('string2')]
最佳答案
将其分解为一个普通循环并具有中间变量并没有错:
id_title_list = []
for elem in root.findall('page'):
title = elem.find('title').text
if title.startswith(('string1', 'string2')):
id_title_list.append((elem.find('id').text, title))
请注意 startswith()
支持作为元组传入的多个前缀。
另一种选择是在 xpath 表达式中进行 startswith()
检查:
id_title_list = [(elem.find('id').text, elem.find('title').text)
for elem in root.xpath('//page[.//title[starts-with(., "string1") or starts-with(., "string2")])]']
请注意,这不适用于 xml.etree.ElementTree
,因为它仅提供对 xpath 表达式的有限支持。 lxml
会处理这个,只需将导入更改为:
from lxml import etree as ET
关于Python:在理解中重复函数调用的更好解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25772145/