extracting numbers from a file, excluding words

Mike Meyer mwm at mired.org
Tue Nov 1 15:35:14 EST 2005


Kristina Kudriaðova <ristinak at gmail.com> writes:

> 1 Nov 2005 09:19:45 -0800, dawenliu at gmail.com <dawenliu at gmail.com>:
>> Hi, I have a file with this content:
>>
>> zzzz zzzzz zzz zzzzz
>> ...
>> xxxxxxx xxxxxxxxxx xxxxx 34.215
>> zzzzzzz zz zzzz
>> ...
>>
>
> Hi,
>
> I'd suggest doing this:
>
> f = file('...')
> for line in f:
>     if 'xxxxxxx xxxxxxxxxx xxxxx' in line:
>         var = float(line[len('xxxxxxx xxxxxxxxxx xxxxx'):].strip())
> f.close()

Alternatively:

start = len('xxxxxxx xxxxxxxxxx xxxxx')
for line in f:
    if line.startswith('xxxxxxx xxxxxxxxxx xxxxx'):
       var = float(line[start:].strip())
       
       <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list