首页 > 解决方案 > 由嵌入的子节点产生的 Elementtree 重复

问题描述

我正在尝试从英国议会记录系统 Hansard 中提取元素。但是 xml 的格式不是特别好。例如,它的结构如下: housecommons/debates/section/section/data housecommons/speeches/section/section/data housecommons/section/section/data

我有可以获取数据的代码,如下例所示。但是,这会导致重复值。我认为原因是我的代码不尊重父子关系,而只是搜索第一个标记之后的每个“部分”标记。

有人可以建议我如何调整我的代码以避免重复吗?

doc = ET.parse(xmlFile)
for house in doc.iter('housecommons'):
    #print ('housecommon', house.tag)
    for debates in house.iter('debates'):
        print ('debates')
        #print (title)
        for section in debates.iter('section'):
            #print ("debates section", section.text)
            #title = ("title", section.find('title').text)
            print('debate section')
            for subsection in debates.iter('section'):
                print("debate subsection", subsection.text)
                #title = ("title", subsection.find('title').text)
                #print(title)

注意这是我要解析的原始 xml 中的事物类型。如果不发布完整的 xml,复杂的结构可能不会完全明显。


<housecommons>
<image src="S6CV0001P0I0103"/>
<col>181</col>
<title>House of Commons</title>
<date format="1981-03-17">Tuesday 17 March 1981</date>
<p id="S6CV0001P0-00854"><i>The House met at half-past Two o'clock</i></p>
<debates>
<section>
<title>PRAYERS</title>
<p id="S6CV0001P0-00855">[MR. SPEAKER <i>in the Chair</i>]</p>
<section>
<title>PRIVATE BUSINESS</title>
<section>
<title>CHARTERHOUSE JAPHET BILL</title>
<p id="S6CV0001P0-00856"><i>Bill read the Third time and passed, with amendments.</i></p>
<section>
<title>BARNSLEY BOROUGH COUNCIL BILL</title>
<p id="S6CV0001P0-00857"><i>Further considered; to be read the Third time.</i></p>
</section>
</section>
</section>
</section>
</housecommons>

标签: pythonxmlelementtree

解决方案


iter(…)方法将递归地遍历它下面的所有 XML 子树(它的孩子、他们的孩子等等)

我想你可能想使用这样的结构

for child in parent:
    if child.tag == 'debates':
         # look further

iter(…)方法在搜索您提供的标签名称时下降了不止一层。这就是出现重复项的原因。


推荐阅读