[Tutor] Python regular expression

Rick Muller rick_muller at yahoo.com
Fri Dec 3 23:31:42 CET 2004


Well, you could *try* ;-).

Okay, here's a one-pass approach:

#!/usr/bin/env python

import re

# Regular expressions stolen from PyCookbook:
#
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/132326
sec = re.compile(r'^\[(.*)\]')
eq = re.compile(r'^([^=]+)=(.*)')

def main(fname='file.ini',pattern='_at'):
    holder = None
    pat = re.compile(pattern)
    for line in open(fname).xreadlines():
        if sec.match(line):
            # We've found a new section. Before we
overwrite the
            # holder dictionary, search through the
last one
            if holder and holder.has_key('Name') and
pat.search(holder['Name']):
                print holder
            # Now create a new dictionary
            section_name = sec.findall(line)[0]
            holder = dict(section_name=section_name)

        if eq.match(line):
            key,val = eq.findall(line)[0][:2]
            holder[key] = val
    return

if __name__ == '__main__': main()


--- Max Noel <maxnoel_fr at yahoo.fr> wrote:

> 
> On Dec 3, 2004, at 21:34, Rick Muller wrote:
> 
> > The file type you mention is also called an INI
> file,
> > and is used for Windows initialization scripts,
> among
> > other things.
> >
> > There's a nice recipe on this in the Python
> Cookbook:
> >
>
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334
> >
> > This will read your file in as a dictionary. You
> can
> > then do searches through lists of the keys:
> >
> > mydict = LoadConfig(file.ini)
> > for key in mydict.keys():
> >     if re.search(key,"_at"):
> do_something(mydict[key])
> 
> 	Given the size of the file, I don't think that's a
> good idea...
> 
> -- Max
> maxnoel_fr at yahoo dot fr -- ICQ #85274019
> "Look at you hacker... A pathetic creature of meat
> and bone, panting 
> and sweating as you run through my corridors... How
> can you challenge a 
> perfect, immortal machine?"
> 
> 

=====
Rick Muller
rick_muller at yahoo.com


		
__________________________________ 
Do you Yahoo!? 
Send a seasonal email greeting and help others. Do good.
http://celebrity.mail.yahoo.com


More information about the Tutor mailing list