考虑到pyparsing的工作原理,我如何在层中实现这一点 [英] How do I implement this in ply, given how pyparsing works

查看:82
本文介绍了考虑到pyparsing的工作原理,我如何在层中实现这一点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我在pyparsing中所做的工作,我正在尝试在ply中实现某些新功能,这对我也是很新的.我该如何编写一个简单的嵌套搜索,例如:

I'm trying to implement something in ply, which I'm very new to, based on what I have done in pyparsing, which I'm also quite new to. How can I write a simple nesting search such as this:

thecontent = pyparsing.Word(pyparsing.alphanums) | '&' | '|' 
parens = pyparsing.nestedExpr( '(', ')', content=thecontent)

使用PLY吗?

推荐答案

您在pyparsing中编写的内容不能很好地转换为PLY,因为,它甚至几乎不是解析器. nestedExpr是快速定义以下形式的表达式的助手:我真的不知道它的含义,但是它被()(或{}[]或其他)包围着,并且它们可以嵌套".解析"{}"分隔的语言(如C)以将简单的函数定义定义为type_spec + identifier + parameter_spec + nestedExpr('{', '}')确实非常方便.假设您正在定义内容以包括&"和'|'运算符,听起来好像您真的要解析一个布尔表达式,包括对括号分组的支持以覆盖运算的优先级.

What you have written in pyparsing does not translate well to PLY because, well, it's barely even a parser. nestedExpr is a helper for quickly defining an expression of the form "I don't really know what's in this, but it's surrounded by ()'s (or {}'s or []'s or whatever), and they can be nested". Really handy to parse a '{}'-delimited language like C, to define a simple function definition as type_spec + identifier + parameter_spec + nestedExpr('{', '}'). Given that you are defining your content to include '&' and '|' operators, it sounds like you really want to parse a boolean expression, including support for parenthetical grouping to override precedence of operations.

pyparsing Wiki的示例"页面上的simpleBool.py示例显示了一些支持布尔表达式解析的测试用例和表达式. But 仍然使用辅助方法infixNotation,该方法隐藏了很多解析器定义步骤,因此,再次将其转换为PLY非常困难.不过,我引用了此示例,因为它可以帮助您弄清解析布尔表达式的过程(包括解析布尔文字,如"True","False"等,并可能添加对"not"运算符的支持).另外,它将为您提供大量免费的测试用例-自助!

The simpleBool.py example on the pyparsing wiki's Examples page shows some test cases and expressions to support boolean expression parsing. BUT it still uses a helper method, infixNotation, which hides much of the parser definition steps, so again, will be difficult to translate to PLY directly. I reference this example though, because it may help you clarify just what is involved in parsing boolean expressions (including parsing boolean literals like "True", "False", etc., and maybe add support for a "not" operator). Also, it will give you a bunch of free test cases - help yourself!

要查看类似于PLY期望的更明确的语法,请查看pyparsing的fourFn.py示例.它早于infixNotation帮助器,因此可以显式建立各种操作优先级. (首先,这种形式的算术运算符优先级实现方式的高雅之处在于使我对解析应用程序产生了兴趣.)

To see a more explicit grammar that is akin to what PLY will expect, look at pyparsing's fourFn.py example. It predates the infixNotation helper, and so builds up the various operation precedences explicitly. (The elegance of this form of implementation of arithmetic operator precedence is largely what got me interested in parsing applications in the first place.)

这篇关于考虑到pyparsing的工作原理,我如何在层中实现这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆