例如,
1. str1 = 'A>1 and A>=3 and B<2 and B<=3 and B<1 ...', should be substituted to:
str1 = 'A>=3 and B<1 ...';
2. str2=['A=1 and B<=2 ...', 'A=1 and B>2 ...'], should be substituted to:
str2=['A=1 ...'], where B is skipped
A,B可以是任何长度的合法python标识符。 str1和str2中都有未知数量的逻辑操作数。
通常的正则表达式搜索方法对于解决此问题非常具有挑战性。任何黑客的想法?
编辑:
为了简化问题,我们只考虑'和'操作,并且所有操作数都按字符串排序,即
'A<x and A<y and A<z' will always appear next to each other
答案 0 :(得分:1)
from itertools import groupby
import re
str1 = "A>1 and A>3 and B<2 and B<3"
comparisions = [s.strip() for s in str1.split("and")]
operands = [re.search(r'(\w+)([<>][=]?)(\w+)',c).groups() for c in comparisions]#
tot={}#total results
for k,g in groupby(operands,lambda x:x[0]):#group by variable1
for arg in g:#arg is the match with list [var1,compareitem,var2]
if k not in tot:tot[k] = {}
if arg[1] in tot[k]:
print("do the overwrite handling!")
tot[k][arg[1]] = arg[2]
#sort tot
sortedkeys = sorted(tot, key=lambda x: x[0])
resub_str = " and ".join([comp+"".join([k+tot[comp][k] for k in tot[comp]]) for comp in sortedkeys])
print(resub_str)
do the overwrite handling!
do the overwrite handling!
A>3 and B<3
[A>1,A>3,B<2,B<3]
等等。COMPARE_ITEM
是<,>,<=,>=
之一VARIABLE1
进行分组,如果我们已经有VARIABLE1
条件,则搜索结果。如果我们有 - 做覆盖。如果没有,只需插入即可。VARIABLE1
对数组进行排序,并使用" and "
您不仅可以通过搜索Var1来改进代码,还可以搜索变量2并为每个使用的变量创建一个参考。
(因此像A<B and A< 4
这样的条件与B>A and 4>A
}相同。