Um... extensible parsing?

holger krekel pyth at devel.trillke.net
Thu May 9 19:22:20 EDT 2002


Philip Swartzleonard wrote:
> holger krekel || Thu 09 May 2002 03:11:54p:
> 
> > Philip Swartzleonard wrote:
> >> 
> >> I am interested in making a program in python that helps people edit
> >> the gameworld definition files used in the Angband and it's many and
> >> various varients. They are a fairly simple text file format, and each
> >> record follow a mostly set pattern. For exapmle, here's the format
> >> for one of the files from ToME:
> > 
> > ask any questions you need to about the following code
> > which should help you get started.
> > 
> > # paste this to your interpreter and
> > # have a /tmp/datafile ready
> > specs=[]
> > for line in open('/tmp/datafile').readlines():
> >     if not line or line.startswith('N'): 
> >         specs.append({})
> >     name,rest=line[:1],line[2:]
> >     if name:
> >         sep = '|' in rest and '|' or ':'
> >         vals=map(lambda x: x.strip(), rest.split(sep))
> >         specs[-1].setdefault(name, []).extend(vals)
> > 
> I:#speed:*hit points:#vision:#armor class:#alertness (or something)
> I:120:3d8:16:22:10


class Monster:
    format='''I:speed:hitpoints:vision:armor_class:alertness
              N:id:species'''.split('\n')
    formatspec={}
    for line in format:
        parts=line.strip().split(':')
        formatspec[parts[0]]=parts[1:]
    def __init__(self, spec):
        for key,values in spec.items():
            fieldnames = self.formatspec.get(key,[])[:] # copy
            if len(fieldnames)<len(values):
                setattr(self,key,values) # unspecified or a flag 
            else:
                for value in values:
                    setattr(self,fieldnames.pop(0),value)

>>> m=Monster(specs[0]) # the previously posted code constructs specs!
>>> m.species
'Black harpy'
>>> m.speed
'120'
>>> m.vision
'16'
>>> m.armor_class
'22'

be careful to specify unique names.

> I don't care about the values of any of this stuff, so it can go from a 
> string in the file to a string in a textbox to a string in the file again 
> and only become an number when actually read by the game =). Thanks for 
> all this though... man i love this language =)

that's why my formatspring doesn't recognize any of this :-)

have fun,

    holger





More information about the Python-list mailing list