Note that there are some explanatory texts on larger screens.

plurals
  1. POPython str.find() overriding Element.find(), how to circumvent?
    text
    copied!<p>I am writing some code that uses the <code>Element.find()</code> method from Python's <code>xml.etree.ElementTree</code> module. However, I am finding that as soon as I start using <code>str.replace()</code>, Python thereafter interprets my calls to <code>object.find()</code> as <code>str.find()</code> rather than <code>Element.find()</code>.</p> <p>I need my code to grab the text from various <code>Element</code> objects from an XML file, and in some cases I need to modify it with <code>str</code> methods. How can I do this without changing how the interpreter interprets <code>object.find()</code>? Here my code:</p> <pre><code>import xml.etree.ElementTree as xml import re import json pattern = re.compile('[a-z,0-9,-]+') c_pattern = re.compile('\[caption[^\]]+\]') c2_pattern = re.compile('\[/caption\]') tree = xml.parse('file.xml') root = tree.getroot() for item in root.iter('item'): if item.find('{http://wordpress.org/export/1.2/}post_type').text == 'post': t = item.find('{http://purl.org/rss/1.0/modules/content/}encoded').text print item.find try: t = t.encode('utf-8') o_cap = re.findall(c_pattern,t) e_cap = re.findall(c2_pattern,t) for item in o_cap: t = t.replace(item,'') for item in e_cap: t = t.replace(item,'') except: t = 'None' print item.find title = item.find('title').text </code></pre> <p>The first <code>print</code> statement returns <code>&lt;bound method Element.find of &lt;Element 'item' at 0x2a7a7d0&gt;&gt;</code>, while the second returns <code>&lt;built-in method find of str object at 0x2b56e00&gt;</code>.</p> <p>I've tried subclassing <code>Element</code>, but I don't know how to make the <code>Element</code> nodes in my XML file become objects of the new subclass. I've also tried simply defining a new method that refers to the <code>Element.find()</code> method, but when I tried to use it the interpreter simply told me that an <code>Element</code> object didn't have a method by the name of my user-defined one.</p> <p>Another way I've thought of is some kind of </p> <pre><code>from xml.etree.ElementTree import Element.find() as Element.some_other_name() </code></pre> <p>but that doesn't work (I've tried a bunch of syntactic variations and they don't work either). Does anyone know what I can/should do to get around this issue?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload