首页 > 解决方案 > pyparsing:忽略任何不匹配的标记

问题描述

我有一个来自我试图解析的游戏的文件。这是一段摘录:

    <stage> id: 50  #Survival Stage
            <phase> bound: 1500  # phase 0   bandit
                    music: bgm\stage4.wma
                    id: 122  x: 100  #milk  ratio: 1
                    id: 30 hp: 50  times: 1
                    id: 30 hp: 50  times: 1  ratio: 0.7
                    id: 30 hp: 50  times: 1  ratio: 0.3
            <phase_end>
    <stage_end>

#表示评论,但仅限于人类读者,而不是游戏的解析器。前两条评论在行尾,但ratio: 1后面#milk不是评论的一部分,它实际上很重要。我认为游戏的解析器会忽略它无法理解的任何标记。有没有办法在pyparsing中做到这一点?

我尝试使用parser.ignore(pp.Word(pp.printables)),但这使它跳过了所有内容。到目前为止,这是我的代码:

import pyparsing as pp

txt = """
<stage> id: 50  #Survival Stage
        <phase> bound: 1500  # phase 0   bandit
                music: bgm\stage4.wma
                id: 122  x: 100  #milk  ratio: 1
                id: 30 hp: 50  times: 1
                id: 30 hp: 50  times: 1  ratio: 0.7
                id: 30 hp: 50  times: 1  ratio: 0.3
        <phase_end>
<stage_end>
"""

phase = pp.Literal('<phase>')
stage = pp.Literal('<stage>') + pp.Literal('id:') + pp.Word(pp.nums)('id') + pp.OneOrMore(phase)
parser = stage

parser.ignore(pp.Word(pp.printables))

print(parser.parseString(txt).dump())

标签: pythonpyparsing

解决方案


原来在股票游戏文件中只有ratio:关键字出现在 a 之后#,所以我用它来定义评论的结尾,如下所示:

parser.ignore(Suppress('#') + SkipTo(MatchFirst([FollowedBy('ratio:'), LineEnd()])))

推荐阅读