python - 由嵌入的子节点产生的 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>
解决方案
该iter(…)
方法将递归地遍历它下面的所有 XML 子树(它的孩子、他们的孩子等等)
我想你可能想使用这样的结构
for child in parent:
if child.tag == 'debates':
# look further
该iter(…)
方法在搜索您提供的标签名称时下降了不止一层。这就是出现重复项的原因。
推荐阅读
- c# - 绑定库错误:如何使方法返回 IDictionary 数组
? - java - 如何在 Spring Boot Java 中运行多个侦听器?
- spring - IntegrationMBeanExporter.stopActiveComponents() 与 gcp pub/sub 生产者一起抛出大量 InterruptedExceptions
- python - 列表中特定列表元素的 Sumproduct
- jenkins - 是否可以在辅助方法或共享库中定义 Jenkins 声明性管道的阶段?
- jira - 在 Jira 描述/评论中添加指向图像附件的链接而不显示缩略图
- grpc - 如何使 Blazor 页面使用来自 gRPC 服务的传入数据更新一个 html 标记的内容
- reactjs - 来源已被 CORS 策略 Spring boot 和 React 阻止
- ruby-on-rails - 检查在 Rails Capybara 中可见不到一秒的元素可见性
- javascript - 为什么我无法使用 AJAX 更新我的 sql 数据库?