parsing string into dict
Tim Arnold
a_jtim at bellsouth.net
Wed Sep 1 13:46:50 EDT 2010
Hi,
I have a set of strings that are *basically* comma separated, but with
the exception that if a comma occur insides curly braces it is not a
delimiter. Here's an example:
[code=one, caption={My Analysis for \textbf{t}, Version 1}, continued]
I'd like to parse that into a dictionary (note that 'continued' gets
the value 'true'):
{'code':'one', 'caption':'{My Analysis for \textbf{t}, Version
1}','continued':'true'}
I know and love pyparsing, but for this particular code I need to rely
only on the standard library (I'm running 2.7). Here's what I've got,
and it works. I wonder if there's a simpler way?
thanks,
--Tim Arnold
The 'line' is like my example above but it comes in without the ending
bracket, so I append one on the 6th line.
def parse_options(line):
options = dict()
if not line:
return options
active = ['[','=',',','{','}',']']
line += ']'
key = ''
word = ''
inner = 0
for c in list(line):
if c in active:
if c == '{': inner +=1
elif c == '}': inner -=1
if inner:
word += c
else:
if c == '=':
(key,word) = (word,'')
options[key.strip()] = True
elif c in [',', ']']:
if not key:
options[word.strip()] = True
else:
options[key.strip()] = word.strip()
(key,word) = (False, '')
else:
word += c
return options
More information about the Python-list
mailing list