Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>With this text (note that I added <code>&lt;icon data="([^"]*)"/&gt;&lt;wind_condition data="([^"]*)"/&gt;</code> at the end because this part isn't in your example) in a file called 'joeljames.txt' :</p> <pre><code>&lt;?xml version="1.0"?&gt;&lt;xml_api_reply version="1"&gt;&lt;weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" &gt;&lt;forecast_information&gt;&lt;city data="Baton Rouge, LA"/&gt;&lt;postal_code data="baton rouge,la"/&gt;&lt;latitude_e6 data=""/&gt;&lt;longitude_e6 data=""/&gt;&lt;forecast_date data="2011-02-22"/&gt;&lt;current_date_time data="2011-02-22 20:06:59 +0000"/&gt;&lt;unit_system data="US"/&gt;&lt;/forecast_information&gt;&lt;current_conditions&gt;&lt;condition data="Cloudy"/&gt;&lt;temp_f data="72"/&gt;&lt;temp_c data="22"/&gt;&lt;humidity data="Humidity: 73%"/&gt;&lt;icon data="/ig/images/weather/cloudy.gif"/&gt;&lt;wind_condition data="Wind: N at 5 mph"/&gt; </code></pre> <p>the following short code</p> <pre><code>import re with open('joeljames.txt','rb') as f: RE = ('humidity data="([^"]*)"/&gt;' '&lt;icon data="([^"]*)"/&gt;' '&lt;wind_condition data="([^"]*)"/&gt;') print re.search(RE,f.read()).groups() </code></pre> <p>or even</p> <pre><code>import re print re.search(('humidity data="([^"]*)"/&gt;' '&lt;icon data="([^"]*)"/&gt;' '&lt;wind_condition data="([^"]*)"/&gt;'), open('joeljames.txt','rb').read()).groups() </code></pre> <p>have result:</p> <pre><code>('Humidity: 73%', '/ig/images/weather/cloudy.gif', 'Wind: N at 5 mph') </code></pre> <p>Nothing more. </p> <p>I know than the priests of XML parsers will say that yoooou MUST use an XML parser because there are some that are very efficient and a coder must be lazy and etc... They are right in case what must be obtained requires complex algorithm.</p> <p>But in case of a simple aim as here, I think justified not to resort to an XML parser, moreover if one doesn't know to use one. Do you ? </p> <p>For my solution, well, you must know regexes, yes... It is necessary to have a minimum of tool when one wants to do something. You must indeed know a language too.....</p> <p>You can use the parser solution, no problem. But now you know that it's possible with regexes too and you can choose.</p> <p>EDIT:</p> <p>To answer to critics that the order of elements may not be always the same:</p> <pre><code>import re print dict(re.findall('(humidity data|icon data|wind_condition data)' '="([^"]*)"/&gt;',open('joeljames.txt','rb').read())) </code></pre> <p>prints</p> <pre><code>{'humidity data': 'Humidity: 73%', 'icon data': '/ig/images/weather/cloudy.gif', 'wind_condition data': 'Wind: N at 5 mph'} </code></pre>
 

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