大数据 爬虫Python AI Sql我滴python路~生活不易 我用python

python 对 xml 文件的解析

2018-07-29  本文已影响2人  Big_Monster

xml文件

xml

其中pathway为整个xml的根节点

xml结构

整个xml结构为

pathway

----entry

--------graphics

----entry

--------graphics

----entry

--------graphics

----....

----relation

--------subtype

----....

需求为讲relation中的attrib中的entry1与entry2提取出来,寻找entry中对应的id

基本思路为:

1. 先获取所有的relation节点,遍历relation节点

2. 获取当前节点的attribute,获取attrib的entry1、entry2属性的值

3. 在entry节点中搜索entry id

4. 构造最后所需的结果

在遍历relation节点,每次都要对entry节点进行搜索,比较浪费时间。

在此可以先构造一个key为id,value为graphics节点 name 的entry字典,之后可以遍历relation的时候获得的

entry1、entry2可以直接访问entry字典获取值,就不需要多层for循环了~

在这里使用的xml解析包为 xml.etree.ElementTree

直接上代码吧=,=

没有设置为markdown文本模式。。。 各位看官将就的看会吧。。也没几行


import xml.etree.ElementTree as ET #解析xml文件的包

import pandas #写入excel需要的包

tree = ET.parse('Pathway_5.xml') #打开xml文件,使用xml.etree进行解析

root = tree.getroot() #获取根节点

entry_list = root.findall('entry') #找到所有的entry节点

relation_list = root.findall('relation') #找到所有的relation节点

entry_dic = {} #构造空字典

#对所有的entry节点进行一次遍历,使用entry的id 作为 字典的key 使用entry内的gene节点的name 作为字典的 value

#这步是为了避免之后每次都要对entry进行遍历查找

#避免了深层次的 for 循环嵌套

for i in entry_list:

    gene = i.findall('graphics') #查找当前entry节点所有的gene节点,避免出现两次

    if len(gene) == 1:

        gene = gene[0]

        if 'name' in gene.attrib:

            entry_dic[i.attrib['id']] = gene.attrib['name'] # 构造key-value

        else:

            print(gene.attrib)

            entry_dic[i.attrib['id']] = 'none'

#为了写入excel作准备

entry1_name = []

entry2_name = []

subtype_name = []

#遍历relation

for i in relation_list:

    #如果当前relation节点不同时存在entry1和entry2则跳到下次for循环

    if 'entry1' not in i.attrib and 'entry2' not in i.attrib:

        print("False relation : %s" % str(relation_list.index(i)))

        continue

    #获得 entry1 和 entry2 的id

    entry1_id = i.attrib['entry1']

    entry2_id = i.attrib['entry2']

    print(entry1_id,entry2_id)

    # 包含当前relation节点的subtype节点出现多个的情况

    subtype_name_list = []

    for k in i.findall('subtype'):

        if 'name' in k.attrib:

            subtype_name_list.append(k.attrib['name'])

        else:

            subtype_name_list.append('')

    #将结果添加到之前列表,pandas写入excel需要列表

    entry1_name.append(entry_dic[entry1_id])

    entry2_name.append(entry_dic[entry2_id])

    subtype_name.append(' '.join(subtype_name_list))

    #写入txt文件

    with open('d.txt','a+') as f:

        f.write('%s \t\t\t\t%s\t\t\t\t%s\n' % (entry_dic[entry1_id],entry_dic[entry2_id],' '.join(subtype_name_list)))

# #写入 excel 文件

# file_name = 'outputs.xlsx' #文件名

# #构造DataFrame结构数据 excel写入需要DataFrame数据

# msg = pandas.DataFrame(data={'entry1_name':entry1_name,'entry2_name':entry2_name,'subtype_name':subtype_name})

# #写入excel

# writer = pandas.ExcelWriter(file_name)

# msg.to_excel(writer,'Sheet1')

# writer.save()


幸好缩进还是保留的....

在这里说下我用到的api

ET.parse('Pathway_5.xml') #解析文件~

tree.getroot() #获取根节点

root.findall('entry') #找到当前节点下的所有tag name 为entry 的节点

.attrib  #获得当前节点的属性

上一篇 下一篇

猜你喜欢

热点阅读