python解析xml文件实例分享

yipeiwu_com5年前Python基础



复制代码 代码如下:

def get_area_list(self):
        """获取地域省份和城市名称字典"""
        page = urllib2.urlopen(self.xml_url).read()
        area_list = {}
        root = ElementTree.fromstring(page)
        #读取xml格式文本
        for onep in root:
            province =  onep.get('name')
            #父标签中的name数据(province中)
            city_list = []
            for onec in onep:
                #子标签中的name数据(city中)
                city = onec.get('name')
                city_list.append(city)
            area_list[province] = city_list
            #返回一个省份与城市关系的字典,即:{省份名称:[城市名称1,城市名称2,···]}
        return area_list

相关文章

用Python实现BP神经网络(附代码)

用Python实现BP神经网络(附代码)

用Python实现出来的机器学习算法都是什么样子呢? 前两期线性回归及逻辑回归项目已发布(见文末链接),今天来讲讲BP神经网络。 BP神经网络 全部代码 https://github.c...

python文件特定行插入和替换实例详解

python文件特定行插入和替换实例详解 python提供了read,write,但和很多语言类似似乎没有提供insert。当然真要提供的话,肯定是可以实现的,但可能引入insert会带...

python实现跨文件全局变量的方法

在使用Python编写的应用的过程中,有时候会遇到多个文件之间传递同一个全局变量的情况。本文就此给出了如下的解决方法供大家参考。 文件1:globalvar.py #!/usr/bi...

python画蝴蝶曲线图的实例

python画蝴蝶曲线图的实例

蝴蝶曲线是由Temple H·Fay发现的可用极坐标函数表示的蝴蝶曲线。 由于此曲线优美, 因此就想把它作为博客favicon.ico,这里我使用pytho matplotlib.pyp...

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...