Pyparsing help
Arnaud Delobelle
arnodel at googlemail.com
Sun Mar 23 03:56:54 EDT 2008
On Mar 22, 9:11 pm, rh0dium <steven.kl... at gmail.com> wrote:
> Hi all,
Hi,
> I am struggling with parsing the following data:
>
> test1 = """
> Technology {
> name = "gtc"
> dielectric = 2.75e-05
[...]
I know it's cheating, but the grammar of your example is actually
quite simple and the values are valid python expressions, so here is a
solution without pyparsing (or regexps, for that matter). *WARNING*
it uses the exec statement.
from textwrap import dedent
def parse(txt):
globs, parsed = {}, {}
units = txt.strip().split('}')[:-1]
for unit in units:
label, params = unit.split('{')
paramdict = {}
exec dedent(params) in globs, paramdict
try:
label, key = label.split()
parsed.setdefault(label, {})[eval(key)] = paramdict
except ValueError:
parsed[label.strip()] = paramdict
return parsed
>>> p = parse(test1)
>>> p['Layer']['PRBOUNDARY']
{'maskName': '', 'defaultWidth': 0, 'color': 'cyan', 'pattern':
'blank', 'layerNumber': 0, 'minSpacing': 0, 'blink': 0, 'minWidth': 0,
'visible': 1, 'pitch': 0, 'selectable': 1, 'lineStyle': 'solid'}
>>> p['Layer']['METAL2']['maskName']
'metal2'
>>> p['Technology']['gridResolution']
5
>>>
HTH
--
Arnaud
More information about the Python-list
mailing list