Ok, here's an example using pyparsing's Dict. -- Paul
testdata = """
/ Flux DSS-DESIGNER, Sample Data
/ Projekt: Set 1
// HYDRAULIK & QUERPROFIL-DATEN
floin_file = set_1.floin
floab_file = set_1.floab
floout_file = floout
flores_file = flores
// REGELUNG
ctrlin_file = set_1.ctrlin
ctrlres_file = ctrl_res
"""
from pyparsing import *
comment = Literal('/') + restOfLine
lhs = Word( alphas, alphanums + "_" )
rhs = Word( alphas, alphanums + "_." )
EQUALS = Literal("=").suppress()
assignment = LineStart() + lhs + EQUALS + rhs
# use pyparsing Dict to create dict-like access to parsed results
grammar = Dict( OneOrMore( Group( assignment ) ) )
grammar.ignore(comment)
results = grammar.parseString( testdata )
# some different example syntaxes for accessing results fields
print "\nShow some different example syntaxes for accessing results like attributes, or dictionary entries"
print "results.flores_file", results.flores_file
print 'results["ctrlres_file"]', results["ctrlres_file"]
for k in results.keys():
print k,"->", results[k]
# can still access results like a list
print "\nJust list out tokens like reading a list"
for entry in results:
print entry[0], ":", entry[1]
# or convert the results to an actual Python list
print "\nOr convert the results to a real Python list"
print results.asList()
----- Original Message -----
From: Robert Pollak <rob...@gm...>
Date: Thursday, March 31, 2005 5:48 pm
Subject: [Pyparsing] Re: empty lines and restOfLine comments
> Here is an update:
> I now use the following, which works fine as long as there are no "="
> characters in the comment lines:
>
> chars = alphanums + "_" + "." + "\\"
> assignment = Word(chars) + Literal("=").suppress() + Word(chars)
>
> cfgFile = file("cfg-snippet")
>
> cfgData = "".join(cfgFile.readlines())
>
> cfgFile.close()
>
> assignments = dict([t for t,s,e in assignment.scanString(cfgData)])
>
> print assignments['floin_file']
>
>
> -------------------------------------------------------
> This SF.net email is sponsored by Demarc:
> A global provider of Threat Management Solutions.
> Download our HomeAdmin security software for free today!
> http://www.demarc.com/Info/Sentarus/hamr30
> _______________________________________________
> Pyparsing-users mailing list
> Pyp...@li...
> https://lists.sourceforge.net/lists/listinfo/pyparsing-users
>
|