在python中,dict的格式,能很好的满足xml中对tree的定义,在一些项目中,使用xml2dict这样的功能,将大大的加强文本分析的能力,直接从tag 中取值,听上去很不错。
有这样的一个框架,可以实现功能。
https://github.com/martinblech/xmltodict
>>> doc = xmltodict.parse("""... <mydocument has="an attribute">
... <and>
... <many>elements</many>
... <many>more elements</many>
... </and>
... <plus a="complex">
... element as well
... </plus>
... </mydocument>
... """)
>>>
>>> doc['mydocument']['@has']
u'an attribute'
>>> doc['mydocument']['and']['many']
[u'elements', u'more elements']
>>> doc['mydocument']['plus']['@a']
u'complex'
>>> doc['mydocument']['plus']['#text']
u'element as well'
最近看了一个很不错的代码,但是,明显如果用这个框架来做,就容易多了。
http://sourceforge.net/projects/yodao-free/files/python-dict/python-dict%201.0.1/pyton-dict.1.0.1.zip/download
这是一个使用python取youdao词典的功能。
其中的get_elements_by_path就是对文进行操作,而失去了xml的格式规范带来的好处,如果处理成dict那么,操作就容易多了。