2016-06-18 9 views
1

このコードは、このxmlドキュメントのコメント数を合計することになっています。すべての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文書で、下部にはの97 + 97となり、コメントは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 
+0

を必要とし、あなたがcommentinfo前に、あなたのコメントタグを終了していない、一番下に気づきました。 – Hashman

答えて

2

注意してください。 <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 
2

ループロジックが間違っています。代わりに

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 

のあなたは自分のコードの一部をテストする上での作業

tree = ET.fromstring(data) 
comments = tree.find('comments').findall('comment') 

count = 0 
for comment in comments: 
    name = comment.find('name').text 
    count += int(comment.find('count').text) 
関連する問題