pyparsing example

让人想犯罪 __ 提交于 2019-12-09 05:34:42

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/8507694/pyparsing-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!