首页 > 解决方案 > PyParsing:使用 SkipTo()、标记数据和可能的 Forward()

问题描述

我正在尝试解析给定以下格式的输入文件。

file = "Begin 'big section header' 
          #... section contents ...
          sub 1: value
          sub 2: value
          ....
          Begin 'interior section header'
          ....
          End 'interior section header'

        End 'big section header'"

返回一个列表,该列表贪婪地抓取标记的部分标题值之间的所有内容

['section header', ['section contents']]

我目前的尝试看起来像这样

import pyparsing as pp

begin = pp.Keyword('Begin')
header = pp.Word(pp.alphanums+'_')
end = pp.Keyword('End')
content = begin.suppress() + header + pp.SkipTo(end + header)

content.searchString(file).asList()

返回

['section header', ['section contents terminated at the first end and generic header found']]

我怀疑我的语法需要更改为某种形式

begin = pp.Keyword('Begin')
header = pp.Word(pp.alphanums+'_')
placeholder = pp.Forward()
end = pp.Keyword('End')

placeholder << begin.suppress() + header
content =  placeholder + pp.SkipTo(end + header)

但我终其一生都无法弄清楚对 Forward 对象的正确分配,而这并没有给我我已经拥有的东西。

标签: python-3.xpyparsing

解决方案


Forward在这种情况下更容易使用的是matchPreviousLiteral

content = begin.suppress() + header + pp.SkipTo(end + matchPreviousLiteral(header))

您正在匹配any end,但您想要的是end与前一个匹配的begin


推荐阅读