Writing Parsers in Python Using Pyparsing

[Pages:21]Writing Parsers in Python Using Pyparsing

Paul McGuire APUG ? May, 2016

Best practices: ... highlighted in the examples

integer = Word('0123456789') phone_number = Optional('(' + integer + ')') + integer + '-' + integer

# pile(r'(\(\d+\))?\d+-\d+')

greet = Word(alphas) + "," + Word(alphas) + "!" greet.parseString("Hello, World!")

Best practice: Don't include whitespace in the parser definition

geo:27.9878,86.9250,8850;crs=wgs84;u=100 geo:-26.416,27.428,-3900;u=100 geo:17.75,142.5,-11033;crs=wgs84;u=100 geo:36.246944,-116.816944,-85;u=50 geo:30.2644663,-97.7841169;a=100;href=



geo-URI geo-scheme geo-path coordinates

= geo-scheme ":" geo-path = "geo" = coordinates p = num "," num [ "," num ]

p crsp crslabel uncp

other val

= [ crsp ] [ uncp ] [";" other]...

= ";crs=" crslabel

= "wgs84" / labeltext = ";u=" uval

Best practice: Start with a BNF

= labeltext "=" val = uval / chartext

ParseResult(scheme='geo', netloc='', path='27.9878,86.9250,8850;crs=wgs84;u=100', params='', query='', fragment='')

patt = r'geo:(-?\d+(?:\.\d*)?),(-?\d+(?:\.\d*)?)(?:,(-?\d+(?:\.\d*)?))?' + r'(?:;(crs=[^;]+))?(?:;(u=\d+(?:\.\d*)?))?'

print(pile(patt).match(tests[0]).groups()) ('27.9878', '86.9250', '8850', 'crs=wgs84', 'u=100')

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download