gpt4 book ai didi

python - pyparsing,转发和递归

转载 作者:太空狗 更新时间:2023-10-29 20:11:45 24 4
gpt4 key购买 nike

我正在使用 pyparsing 来解析 vcd(值更改转储)文件。本质上,我想读入文件,将其解析为内部字典,然后操作这些值。

在不详细介绍结构的情况下,我的问题出现在识别嵌套类别方面。

在 vcd 文件中,您有“范围”,其中包括连线和可能更深(嵌套)的范围。将它们想象成关卡。

所以在我的文件中,我有:

$scope module toplevel $end
$scope module midlevel $end
$var wire a $end
$var wire b $end
$upscope $end
$var wire c $end
$var wire d $end
$var wire e $end
$scope module extralevel $end
$var wire f $end
$var wire g $end
$upscope $end
$var wire h $end
$var wire i $end
$upscope $end

因此,“toplevel”包含一切 (a - i),“midlevel”包含 (a - b),“extralevel”包含 (f - g),等等。

这是我解析此部分的代码(片段):

scope_header = Group(Literal('$scope') + Word(alphas) + Word(alphas) + \
Literal('$end'))

wire_map = Group(Literal('$var') + Literal('wire') + Word(alphas) + \
Literal('$end'))

scope_footer = Group(Literal('$upscope') + Literal('$end'))

scope = Forward()
scope << (scope_header + ZeroOrMore(wire_map) + ZeroOrMore(scope) + \
ZeroOrMore(wire_map) + scope_footer)

现在,我认为发生的是,当它到达每个范围时,它会跟踪每个“级别”,我最终会得到一个包含嵌套范围的结构。但是,它会出错

$scope module extralevel $end

说它期望'$upscope'。

所以我知道我没有正确使用递归。有人可以帮我吗?如果我需要提供更多信息,请告诉我。

谢谢!!!!

最佳答案

根据你的定义,一个作用域不能包含另一个作用域,后面跟着一些映射,后面跟着另一个作用域。

如果解析器具有打印其解析树的 Debug模式,您将能够立即看到这一点。但简而言之,你是说有零个或多个映射,后面跟着零个或多个范围,然后是零个或多个映射,所以如果有一个范围,后面跟着一个映射,你已经传递了范围字段,所以任何更多的范围都是无效的。如果 pyparsing 使用的语言支持“或”,您可以使用:

scope << (scope_header + ZeroOrMore((wire_map | scope)) + scope_footer)

关于python - pyparsing,转发和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4140884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com