extracting numbers from a file, excluding words

Micah Elliott mde at micah.elliott.name
Tue Nov 1 16:52:51 EST 2005


On Nov 01, Mike Meyer wrote:
> 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())

To refine this even further, I'll add that 'xxx...' is an ugly pattern
to repeat, and prone to mistyping, so add a tempvar and apply DRY::

    pattern = 'xxxxxxx xxxxxxxxxx xxxxx'
    start = len(pattern)
    for line in f:
        if line.startswith(pattern):
           var = float(line[start:].strip())

-- 
_ _     ___
|V|icah |- lliott  http://micah.elliott.name  mde at micah.elliott.name
" "     """



More information about the Python-list mailing list