开发者

Implementing logic from text

开发者 https://www.devze.com 2023-03-14 07:15 出处:网络
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

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',开发者_如何学JAVA '(', '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??


This sounds like a task for Pyparsing:

The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. The pyparsing module provides a library of classes that client code uses to construct the grammar directly in Python code.

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号