python - 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())
解决方案
原来在股票游戏文件中只有ratio:
关键字出现在 a 之后#
,所以我用它来定义评论的结尾,如下所示:
parser.ignore(Suppress('#') + SkipTo(MatchFirst([FollowedBy('ratio:'), LineEnd()])))
推荐阅读
- firebase - Firebase 电话身份验证使之前运行的 iOS 上的应用程序崩溃
- python - Python-Selenium:如何访问网站的这一部分?
- django - Django仅在外键未保存为属性时过滤相关模型
- bash - 每次将带有 awk 的时间戳放在文件的开头
- flutter - 如何在颤动中延迟数据查看 3 秒
- html - 如何在 ReactJS 中动态设置图像大小?
- python - 安装有关 PIP Python 的问题
- shared-libraries - 静态链接共享库的优点
- c - 悬空指针有什么问题?
- c - 使用 -lcrypto 编译 C 代码但 perror() 在运行时打印“没有这样的文件或目录”