gpt4 book ai didi

python - 求和所有 xml 标记值?

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:40 29 4
gpt4 key购买 nike

此代码应该计算此 xml 文档中的评论数。

import urllib
import xml.etree.ElementTree as ET

url = 'http://python-data.dr-chuck.net/comments_42.xml'

print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
print data
for line in data:
tree = ET.fromstring(data)
comments = tree.findall('comments')

name = comments[0].find('comment').find('name').text
count = comments[0].find('comment').find('count').text
count = int(count)
count = count + count
print count

但它只显示第一个comment标签上的评论数,然后将其添加到自己然后停止。

这是输出。上面是xml文档,下面是count(194,也就是97+97,只有 Romina),这是不正确的。它应该是文件中所有评论的总和,而不仅仅是 Romina 的

如何获取文件中所有评论的总和?

Retrieving http://python-data.dr-chuck.net/comments_42.xml
Retrieved 4189 characters
<?xml version="1.0" encoding="UTF-8"?>
<commentinfo>
<note>This file contains the sample data for testing</note>

<comments>
<comment>
<name>Romina</name>
<count>97</count>
</comment>
<comment>
<name>Laurie</name>
<count>97</count>
</comment>
<comment>
<name>Bayli</name>
<count>90</count>
</comment>
<comment>
<name>Siyona</name>
<count>90</count>
</comment>
<comment>
<name>Taisha</name>
<count>88</count>
</comment>
<comment>
<name>Ameelia</name>
<count>87</count>
</comment>
<comment>
<name>Alanda</name>
<count>87</count>
</comment>
<comment>
<name>Prasheeta</name>
<count>80</count>
</comment>
</commentinfo>

194

最佳答案

注意细微的变化。因为<comments>包含几个 <comment>标签,我们首先需要找到所有的标签,然后我们才能遍历它们并找到 <count>标签。

import urllib
import xml.etree.ElementTree as ET

url = 'http://python-data.dr-chuck.net/comments_42.xml'

uh = urllib.urlopen(url)
data = uh.read()

tree = ET.fromstring(data)
comments = tree.find('comments').findall('comment')
total_count = 0
for comment in comments:
count = comment.find('count').text
count = int(count)
total_count += count
print total_count
>> 2553

关于python - 求和所有 xml 标记值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37897822/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com