python-3.x - 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 对象的正确分配,而这并没有给我我已经拥有的东西。
解决方案
比Forward
在这种情况下更容易使用的是matchPreviousLiteral
:
content = begin.suppress() + header + pp.SkipTo(end + matchPreviousLiteral(header))
您正在匹配any end
,但您想要的是end
与前一个匹配的begin
。
推荐阅读
- java - Log4j2 SmtpAppender 包含没有堆栈跟踪源代码位置的异常
- ios - 如何修复此错误“找不到架构‘x86_64’的模块‘CzsBleSdk’;找到:arm64,arm”
- firebase - 无法从 Firebase 函数访问数据库
- sql - 计算排名并按照顺序应用
- node.js - NodeJS在函数中调用readline
- scala - 监控具体集合的运行时使用
- javascript - 无法移除视频来源属性
- java - kotlin.TypeCastException: null 不能转换为非 null 类型 android.graphics.Bitmap
- ios - 在 iOS 上运行离子应用程序时出现 NSURLConnection 错误 1100
- amazon-web-services - 如何使两个ec2实例在内部相互连接