pyparsing 示例

10 投票
1 回答
11003 浏览
提问于 2025-04-17 08:22

这是我第一次尝试使用pyparsing,我想问一下如何过滤这行示例:

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

希望能得到像这样的输出:1,52.125133215643,21.031048525561,116.898812

总的来说,我对pyparsing的逻辑理解有些困难,所以任何关于这个例子的帮助都非常感谢。谢谢!

1 个回答

27

你可以从下面这样的代码开始:

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)

这个脚本的输出结果是:

[52.125133215643, 21.031048525561, 116.898812]

补充一下:你可能还想看看 lepl,这是一个类似的库,文档写得很不错。与上面的代码等效的脚本是:

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)

撰写回答