您的位置:首页 > 编程语言 > Python开发

Python.Extracting Data from XML

2016-07-22 20:12 393 查看
The program will prompt for a URL, read the XML data from that URL using urllib and
then parse and extract the comment counts from the XML data, compute the sum of the numbers in the file.

XML地址:http://python-data.dr-chuck.net/comments_290545.xml  (Sum
ends with 57)

Python源码:

import urllib
import xml.etree.ElementTree as ET

url = raw_input('Enter location: ')
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
tree = ET.fromstring(data)

counts = tree.findall('.//comment')

lst = list()
for count in counts:
count = int(count.find('.//count').text)
lst.append(count)
print sum(lst)运行结果:
Enter location: http://python-data.dr-chuck.net/comments_290545.xml Retrieved 4204 characters
2457
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: