简体   繁体   中英

What kind of parser should I use in Python to match a text against a boolean condition

Let's say I have a text that reads

John likes apple, banana and grapes

and I have a boolean expression something like

((banana & apple) & (!orange)) || (peach)

which basically means that the text should ((contain both the words "banana" and the word "apple") and (should not contain "orange")) or (contains the word "peach").

Applying the above boolean logic to the text we need to get the result as True (because it indeed contains banana and apple and does not contain the word orange.

What is an easy way to implement such boolean rules in Python? Is there a framework that can take a chunk of text and an expression and evaluate it? The expressions can be written in a way to satisfy the requirements of the framework if necessary.

So far, I am parsing the Python text using a simple code that will keep track of the paranthesis and so on which is not so efficient and does not provide an opportunity to explore more flexible expressions.

Thanks

I don't know if you want to do it by providing a text to be parsed but I have this in mind:

class String(str):
    def __call__(self, *args):
        s = str(self)
        for arg in args:
            if arg not in s:
                return False
        return True


if __name__ == '__main__':
    s1 = String("John likes apple, banana and grapes")
    print(s1("apple", "banana") and not s1("orange"))  # True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM