Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 解析XML,并对;“计数”;,为什么;计数=tree.findall(';comment/coment';)”;生成[]_Python_Xml_Python 2.7_Xml Parsing - Fatal编程技术网

Python 解析XML,并对;“计数”;,为什么;计数=tree.findall(';comment/coment';)”;生成[]

Python 解析XML,并对;“计数”;,为什么;计数=tree.findall(';comment/coment';)”;生成[],python,xml,python-2.7,xml-parsing,Python,Xml,Python 2.7,Xml Parsing,XML数据格式: import urllib import xml.etree.ElementTree as ET url = raw_input('Enter location: ') print 'Retrieving', url uh = urllib.urlopen(url) data = uh.read() print data print 'Retrieved',len(data),'characters' tree = ET.fromstring(data) counts

XML数据格式:

import urllib
import xml.etree.ElementTree as ET


url = raw_input('Enter location: ')

print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print data
print 'Retrieved',len(data),'characters'
tree = ET.fromstring(data)

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

马蒂亚斯
97

根据您提供的XML,
comment/comment
不匹配任何内容

您可能打算使用:

<comment>
  <name>Matthias</name>
  <count>97</count> 
</comment>
然后,如果要对计数求和:

tree.findall('.//comment/count')
你应使用:

sum(int(c.text) for c in tree.findall('.//comment/count'))
这将检索包含“name”和“count”的所有子树。要查找“count”标记中的所有值,只需使用for循环:

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

您可以从那里获得总和。

您可以使用python3中的以下代码进行总和:

for values in counts:
    print int(values.find('count').text)

XML数据格式类似于XML数据格式:Matthias 97我尝试了您的代码,但它显示了语法错误,比如“无法使用它表示无法在上使用绝对路径elelment@user5584054你确定xpath的开头有一个点吗?对不起,我的错,它确实起作用了。谢谢!还有一个问题,command tree.findall('.//comment/count')没有生成列表,有点让人困惑。你能解释一下吗?
counts = tree.findall('.//count')

total =0

for item in counts:

    total +=int(item.text)

print("Sum :",total)