0

I am parsing a large XML file using Python and stuck on a condition removal of an element. I have checked the logic as has another person, however for whatever reason it still doesn't work. Essentially I am trying to remove Non-Preffered Terms that are non-English as we don't require them in our system. So a term might look like the following

<Subject>
<Terms>
<Non-Preferred_Term>
<Term_Text>hanging buttress</Term_Text>
<Term_Language>Dutch</Term_Language>
</Non-Preferred_Term>
More terms...
</Terms>
</Subject>

Essentially my logic goes like this find the terms Element, find the non-preferred-term, look at the language for each and if the language doesn't match English then remove the term.

for terms in term.iterfind ("Terms"):
    for term in terms.iterfind ("Non-Preferred_Term"):
        for language in term.iterfind ("Term_Language"):
            if language.text != ("English"):
                print (language.text)
                term.remove (term)
                print ("term deleted")

When I run the script on my test file it seems to work in that I get a print out of each language text that isn't English as it runs followed by term deleted. However when I look at the ouput file the none english terms are still in the file. When I try it on my 700mb file it seems to generally work but crashes out sometimes with x is not in list.

Any suggestions?

3
  • This term.remove(term) looks suspect. You can't remove an object from itself... can you?
    – Sam
    Mar 2, 2015 at 17:52
  • 1
    @Sam Why not? x=[]; x.append(x); x.remove(x) works just fine :P Edit: Not saying it's the correct thing to do here though. Mar 2, 2015 at 17:53
  • that my error it should indeed be terms.remove(term). I am removing the child term from the terms list.
    – ADWALSH
    Mar 3, 2015 at 10:54

1 Answer 1

1

This is most likely a reference issue. You have:

for terms in term.iterfind('Term'):
    for term in terms:

So term is a variable before any of the loops, but then you re-use that name in the inner for loop.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.