从文本实现逻辑
我有一个程序以文本形式接收输入,例如:
IF (A.4.1-1/1 OR A.4.1-1/2) AND A.4.4-1/9 AND (A.4.4-1/12 OR A.4.4-1/13 OR A.4.4-1/14 OR A.4.4-1/15) THEN R ELSE N/A
其中 A.4.1-1/1
等是值为 TRUE 或 FALSE
的变量。到目前为止,我已经将上面示例的文本解析为逻辑部分,我有一个如下所示的列表:
['IF', '(', 'A.4.1-1/1', 'OR', 'A.4.1-1/2', ')', 'AND', 'A.4.4-1/9', 'AND', '(', 'A.4.4-1/12', 'OR', 'A.4.4-1/13', 'OR', 'A.4.4-1/14', 'OR', 'A.4.4-1/15', ')', 'THEN', 'R', 'ELSE', 'N/A']
我只是想知道是否可以实际执行此列表上的逻辑,例如将所有这些组合到所需的 python 语句中并提供结果。我不确定要开始我在一些网站上读到我应该使用自上而下的解析器?
I have a program which recieves inputs in the form of text for example :
IF (A.4.1-1/1 OR A.4.1-1/2) AND A.4.4-1/9 AND (A.4.4-1/12 OR A.4.4-1/13 OR A.4.4-1/14 OR A.4.4-1/15) THEN R ELSE N/A
where A.4.1-1/1
etc. are variables with a value TRUE or FALSE
. so far i have parsed up the text into the logical parts for the above example I have a list that looks like this:
['IF', '(', 'A.4.1-1/1', 'OR', 'A.4.1-1/2', ')', 'AND', 'A.4.4-1/9', 'AND', '(', 'A.4.4-1/12', 'OR', 'A.4.4-1/13', 'OR', 'A.4.4-1/14', 'OR', 'A.4.4-1/15', ')', 'THEN', 'R', 'ELSE', 'N/A']
I am just wondering is it possible to actually perform the logic on this list like combine all this up into the rquired python statements and provide the result. I am not sure were to start I have read on some sites that I should use a top down parser??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这听起来像是 Pyparsing 的任务:
您将能够快速定义语法(而不是使用正则表达式)和特定的解析操作。我使用 Pyparsing 在不到 300 行的代码中构建了非常丰富的迷你语言。
This sounds like a task for Pyparsing:
You will be able to quickly define your grammar (instead of playing with regular expressions) and specific parsing actions. I have built very rich mini-languages using Pyparsing in under 300 lines of code.
我不是 Python 爱好者,但我使用 JavaCC 在 Java 中完成了类似的事情。您需要做的是为您的语言编写语法(格式如< a href="http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form" rel="nofollow">EBNF,但这取决于解析器生成器),然后使用程序像JavaCC一样为其生成一个解析器,这将为您提供一个更方便的解析树操纵。
您应该能够找到许多有用的示例,因为输入的语法看起来并不太不寻常(布尔运算符、括号表达式和 if-then-else 语句可能是最常见的用例)。
您可能会发现本页列出的 Python 库之一很有用。
I'm not a Python guy, but I've done similar things in Java using JavaCC. What you'll want to do is write a grammar for your language (in a format such as EBNF, but it depends on the parser generator), then use a program like JavaCC to generate a parser for it, which will give you a parse tree that is more convenient to manipulate.
You should be able to find many useful examples, since the grammar of your input doesn't look too unusual (boolean operators, parenthesized expressions, and if-then-else statements are probably some of the most common use-cases for this).
You might find one of the Python libraries listed on this page useful.