multiple pattern regular expression
Arnaud Delobelle
arnodel at googlemail.com
Sat Apr 26 02:53:51 EDT 2008
Chris Henry <chrishenry.ni at gmail.com> writes:
> On Apr 25, 8:37 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
>> micron_make <micro_pass... at yahoo.com> writes:
>> > I am trying to parse a file whose contents are :
>>
>> > parameter=current
>> > max=5A
>> > min=2A
> [snip]
>> If every line of the file is of the form name=value, then regexps are
>> indeed not needed. You could do something like that.
>>
>> params = {}
>> for line in file:
>> name, value = line.strip().split('=', 2)
^ 1, obviously!
>> params[name] = value
>>
>> (untested)
>> Then params should be the dictionary you want.
>>
> I'm also interested in this problem. While this solution works, I'm
> looking for solution that will also check whether the parameter name/
> value is of a certain pattern (these patterns may be different, e.g.
> paramA, paramB, paramC may take integers value, while paramD may take
> true/false). Is there a way to do this easily?
>
> I'm new to Python and the solution I can think off involve a loop over
> a switch (a dictionary with name->function mapping). Is there other,
> more elegant solution?
Sounds good to me.
E.g.
def boolean(x):
if x == 'true':
return True
elif x == 'false'
return False
else:
raise ValueError("Invalid boolean: '%s'" % x)
paramtypes = { 'paramA': int, ..., 'paramD': boolean }
#Then
for line in file:
line = line.strip()
if not line: continue
name, value = line.split('=', 1)
if name in paramtypes:
try:
value = paramtypes[name](value)
except ValueError, e:
# handle the error
value = e
else:
# What to do for untyped parameters
pass
params[name] = value
--
Arnaud
More information about the Python-list
mailing list