Python3用ElementTree解析xml文件

Python3用ElementTree解析xml文件

在家自己用ElementTree对专利文件的.xml文件进行提取,想要找出专利的标题和摘要,解析提取摘要的时候还算顺利,但是提取标题的时候总是出来两行,后来仔细翻阅了xml文件之后,才发现里面有两个同名标。后来找了一篇博客(链接在下方),它的xml文件里有四个country标签,用country的attribute进行筛选,最后成功的print出自己想要的那个文本。

这里是引用 python3之xml处理(xml.etree.ElementTree)

发现四个同名标签

import xml.etree.ElementTree as ET
xml_string ='''
<data data_attrib="hello xml" data_attrib2="hello xml2">
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria">textqqq</neighbor>
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2012</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
    <country name="China">
        <rank>8</rank>
        <neighbor direction="E" name="Japan">I am Japan</neighbor>
    </country>
</data>

'''
root = ET.fromstring(xml_string)
for country in root.findall('country'):
    print(country.tag, country.attrib)

结果如下

country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}
country {'name': 'China'}

我们想得到的是name为China 的country标签下的内容,所以输入以下内容

if country.attrib["name"] == "China":
    neighbor = country.find("neighbor")
    print(neighbor.text)

最后得到的结果

I am Japan

但是到了我这个专利文本的时候,直接照搬代码前面部分还是ok的,可以看到有两个InventionTitle标签

import xml.etree.ElementTree as ET

tree = ET.parse('C:/Users/Administrator/Desktop/2021.xml')
root = tree.getroot()
for BibliographicData in root:  # 找到标题
    # print(BibliographicData.tag, BibliographicData.attrib)
    for InventionTitle in BibliographicData.findall('{http://www.sipo.gov.cn/XMLSchema/business}InventionTitle'):
        print(InventionTitle.tag, InventionTitle.attrib)
{http://www.sipo.gov.cn/XMLSchema/business}InventionTitle {'lang': 'zh', 'dataFormat': 'original', 'sourceDB': 'national office', 'processingType': 'original', 'creator': '03'}
{http://www.sipo.gov.cn/XMLSchema/business}InventionTitle {'id': 'title1'}

加上选择语句

if InventionTitle.attrib["id"] == "title1":
	print(InventionTitle.text)

然后就会报错

Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/pythonProject/main.py", line 14, in <module>
    if InventionTitle.attrib["id"] == "title1":
KeyError: 'id'

竟然出现了KeyError,但是前面已经出现了id,所以我就很纳闷。网上找到了dict.has_key(key)这个函数来判断key是否在字典里,但是很可惜Python3就把这个函数删除了(Python2依然可以使用)我们可以采用 if key in dict:
这个判断语句来判断key在不在dict里,最后的结果是在dict里。

if 'id' not in InventionTitle.attrib:
	print('false')
else: print('true')

最后通过下面两行代码得出了想要的结果

if 'id' in InventionTitle.attrib:
	print(InventionTitle.text)

代码运行结果
在这里插入图片描述
后来找了学长询问之后,是因为两个InventionTitle标签里并不是都包含
‘id’,上面的country可以这样用是因为它的四个标签下面都有’name’属性。由于有的InventionTitle标签没有’id’,所以在进行for循环的时候可能先被循环到的是没有’id’的标签,那么就会出现key error。所以我们直接用if语句来筛选就可以了。

后面进行大批量导入xml文件之后,摘要部分也出现了问题,因为刚开始是看着其中一个xml文件编写的代码,有的文本格式跟第一个不太一样,导致输出很多不需要的内容,最后还是通过if来筛选,筛选完的内容那个就可以用xxx.attrib[‘id’] == 'xxx’来选出自己想要的内容。

for Abstract in root:  # 找到摘要
    for Paragraphs in Abstract.findall('{http://www.sipo.gov.cn/XMLSchema/base}Paragraphs'):
        if 'num' in Paragraphs.attrib:
            if Paragraphs.attrib["num"] == "0001":
                abstract = Paragraphs.text
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值