gpt4 book ai didi

python - 读取大型 XML 时如何系统地避免或忽略超出范围的子索引

转载 作者:太空宇宙 更新时间:2023-11-03 16:41:17 24 4
gpt4 key购买 nike

我正在阅读一个包含超过 106.000 个条目的大型 XML。每个条目都是一组研究人员提供的大量信息。我做了一个阅读功能。

但是,如果任何时候缺少任何信息,我会得到

IndexError: child index out of range

当 child 失踪时,有没有办法告诉程序忽略

由于数据的多样性,我可能会为每个单独收集的数据提供不同大小的信息。

每次都检查可能不是一个好主意,例如:

if root[0]0][0][0]:
tot_nac_2011 = int(root[0][0][0][0].attrib['TOT-BIBL-PERIODICO-NAC']

这是我的代码

from xml.etree import ElementTree
extended = ElementTree.parse('0000301510136952_2014_estendido.xml')

def read_researcher(extended):
root = extended.getroot()
members = []
for each in range(len(root[0])):
group_id = root.attrib['NRO-ID-GRUPO']
research_id = root[0][each].attrib['NRO-ID-CNPQ']
name = root[0][each].attrib['NOME-COMPLETO']
tit = root[0][each].attrib['TITULACAO-MAXIMA']
sex = root[0][each].attrib['SEXO']
tot_nac_2011 = int(root[0][each][0][0].attrib['TOT-BIBL-PERIODICO-NAC'])
tot_nac_2014 = int(root[0][each][0][3].attrib['TOT-BIBL-PERIODICO-NAC'])
tot_int_2011 = int(root[0][each][0][0].attrib['TOT-BIBL-PERIODICO-INT'])
tot_int_2014 = int(root[0][each][0][3].attrib['TOT-BIBL-PERIODICO-INT'])
tot_bbl_2011 = int(root[0][each][0][0].attrib['TOT-BIBL'])
tot_bbl_2014 = int(root[0][each][0][3].attrib['TOT-BIBL'])
members.append(researchers.Researcher(group_id, research_id, name, tit, sex, tot_nac_2011, tot_nac_2014, tot_int_2011, tot_int_2014, tot_bbl_2011, tot_bbl_2014))
return members

最佳答案

要回答您的具体问题:通过 try/ except 使用异常处理,并处理从子元素提取属性值时可能发生的相关错误。这有点像 EAFP编程风格。还有LBYL一个。

我还会使用中间字典来处理 Researcher 对象初始化参数来改进代码,将 group_id 从循环下移动,因为我们是从根元素。

代码:

from xml.etree import ElementTree


extended = ElementTree.parse('0000301510136952_2014_estendido.xml')


def get_value(item, index, value):
try:
return int(item[index].attrib[value])
except (IndexError, KeyError, AttributeError, ValueError):
# TODO: log
return None


def read_researcher(extended):
root = extended.getroot()
group_id = root.attrib['NRO-ID-GRUPO']

members = []
for item in root[0]:
subitem = item[0]
researcher = {
"group_id": group_id,
"research_id": item.attrib.get('NRO-ID-CNPQ'),
"name": item.attrib.get('COMPLETO'),
"tit": item.attrib.get('TITULACAO-MAXIMA'),
"sex": item.attrib.get('SEXO'),
"tot_nac_2011": get_value(subitem, 0, 'TOT-BIBL-PERIODICO-NAC'),
"tot_nac_2014": get_value(subitem, 3, 'TOT-BIBL-PERIODICO-NAC'),
"tot_int_2011": get_value(subitem, 0, 'TOT-BIBL-PERIODICO-INT'),
"tot_int_2014": get_value(subitem, 3, 'TOT-BIBL-PERIODICO-INT'),
"tot_bbl_2011": get_value(subitem, 0, 'TOT-BIBL'),
"tot_bbl_2014": get_value(subitem, 3, 'TOT-BIBL'),
}

members.append(researchers.Researcher(**researcher))
return members

关于python - 读取大型 XML 时如何系统地避免或忽略超出范围的子索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com