Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyparsing example

It is my first attempt to use pyparsing and I'd like to ask how to filter this sample line:

survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''

to get output like: 1,52.125133215643,21.031048525561,116.898812

In general I have problem with understanding pyparsing logic so any help with this example will be appreciated. Thanks

like image 601
daikini Avatar asked Dec 14 '11 16:12

daikini


People also ask

What is Pyparsing?

The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. The pyparsing module provides a library of classes that client code uses to construct the grammar directly in Python code.

How do I install Pyparsing?

Open your Linux terminal or shell. Type “ pip install pyparsing ” (without quotes), hit Enter. If it doesn't work, try "pip3 install pyparsing" or “ python -m pip install pyparsing “. Wait for the installation to terminate successfully.


1 Answers

You could start with something like this:

from pyparsing import *

survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''

number = Word(nums+'.').setParseAction(lambda t: float(t[0]))
separator = Suppress(',')
latitude = Suppress('LA') + number
longitude = Suppress('LN') + number
elevation = Suppress('EL') + number

line = (Suppress('GPS,PN1,')
        + latitude
        + separator
        + longitude
        + separator
        + elevation)

print line.parseString(survey)

The output of the script is:

[52.125133215643, 21.031048525561, 116.898812]

Edit: You might also want to consider lepl, which is a similar library that's pretty nicely documented. The equivalent script to the one above is:

from lepl import *

survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''

number = Real() >> float

with Separator(~Literal(',')):
    latitude = ~Literal('LA') + number
    longitude = ~Literal('LN') + number
    elevation = ~Literal('EL') + number

    line = (~Literal('GPS')
             & ~Literal('PN1')
             & latitude
             & longitude
             & elevation)

print line.parse(survey)
like image 58
jcollado Avatar answered Nov 15 '22 20:11

jcollado