mardi 19 janvier 2021

IF statement with AND/OR conditions defined by a string

I have an input string ('text') that I want to check if it includes a series of words through a complex AND/OR combination, for instance something like:

if ("alarm" in text or "arm" in text or "clock" in text) and ("which" in text or ("list" in text or "least" in text) or "do i have" in text):

This AND/OR combination example could be expressed in a simple way as:

'(alarm|arm|clock)&(which|(list|least)|do I have)'

So my goal is to have strings in a simple format, such as the previous one, stored in a file and to have my python code accessing it and performing an IF check on 'text' according to that AND/OR combination. I don't mind changing a bit the format (like swapping '|' for '/' or '&' for '+') if the format is still humanly visually simple.

I didn't find any way to adjust the number of AND/OR in an IF statement according to a string and trying to create a custom function that would carefully analyse the string and check one by one the words in the order dictated by the generic parenthesis hierarchy proved to be too challenging for me.

I read that regular expressions could be the solution here but after going through its documentation I didn't figure out a way to do those AND/OR combinations taking into account that the words in 'text' could come in any order. I think regex is just too powerful for the simple "word in text" check that I want to make.

Is there any other more elegant way to do this that I am missing?

Aucun commentaire:

Enregistrer un commentaire