pyparsing example

后端 未结 1 2094
有刺的猬
有刺的猬 2021-02-08 17:40

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.898         


        
1条回答
  •  梦如初夏
    2021-02-08 18:22

    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)
    

    0 讨论(0)
提交回复
热议问题