0

Why is this not accepting i as a variable in my for loop? here is my code:

import urllib
import xml.etree.ElementTree as ET

url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/comments_42.xml'

while True:
    uh = urllib.urlopen(url)
    data = uh.read()
    tree = ET.fromstring(data)

    counts = tree.findall('.//count')
    print "counts[0] = ", counts[0]
    print "counts[0].text = ", counts[0].text
    print "type(int(counts[0].text)) = ", type(int(counts[0].text))
    total = 0
    for i in counts:
        total = total + int(counts[i].text)
    print total
    break

I get the following output: enter image description here

A sample of the XML I want to parse is here: enter image description here

Im trying to add up the "count"s in the text.

1 Answer 1

1

counts - is an array of elements. Here for i in counts: i will be an element. You can write like that

for elem in counts:
    total += int(elem.text)

or

for index in range(0, len(counts)):
    total += int(counts[index].text)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.