Python高级编程技巧实战学习_Day14

学习资源传送门:https://www.bilibili.com/video/BV1b5411s76z?p=24

(一)学习内容:如何解析简单的xml文档

(二)解决方案

 

注:现在有 xmltodict 模块,它是一个用来处理xml数据的很方便的模块。包含两个常用方法parse和unparse 。xmltodict速度非常快(基于 Expat),并且具有内存占用量小的流模式,适用于大型 XML 转储

(1)parse

  • xmltodict.parse()方法可以将xml数据转为python中的dict字典数据

(2)unparse

  • xmltodict.unparse()方法可以将字典转换为xml字符串

(三)代码

(1)简单尝试

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/13 9:24
# @Author  : Qiufen.Chen
# @Email   : 1760812842@qq.com
# @File    : xml_to_dict.py
# @Software: PyCharm

import json
import xmltodict

print(json.dumps(xmltodict.parse("""
 <mydocument has="an attribute">
   <and>
     <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
    </plus>
 </mydocument>
  """), indent=4))

# output
'''
{
    "mydocument": {
        "@has": "an attribute",
        "and": {
            "many": [
                "elements",
                "more elements"
            ]
        },
        "plus": {
            "@a": "complex",
            "#text": "element as well"
        }
    }
}
'''

xml_dict = {
    "xml": {
        "ToUserName": "gh_866835093fea",
        "FromUserName": "ogdotwSc_MmEEsJs9-ABZ1QL_4r4",
        "CreateTime": "1478317060",
        "MsgType": "text",
        "Content": u"你好",
        "MsgId": "6349323426230210995",
    }
}

xml_str = xmltodict.unparse(xml_dict, pretty=True)
print(xml_str)

# output
'''
<?xml version="1.0" encoding="utf-8"?>
<xml>
	<ToUserName>gh_866835093fea</ToUserName>
	<FromUserName>ogdotwSc_MmEEsJs9-ABZ1QL_4r4</FromUserName>
	<CreateTime>1478317060</CreateTime>
	<MsgType>text</MsgType>
	<Content>你好</Content>
	<MsgId>6349323426230210995</MsgId>
</xml>
'''

(2)进阶使用 

import xmltodict

def handle_artist(_, artist):
    artist['_id'] = artist['name']
    print(artist['name'])
    return True

fin = r'E:\data\uniprot_sprot.xml.gz'
xmltodict.parse(GzipFile(fin), item_depth=2, item_callback=handle_artist)

————————————————————

参考:

(1)https://github.com/martinblech/xmltodict

(2)https://blog.csdn.net/qq_38923792/article/details/93248635?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.control

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值