如何从python中的布尔逻辑表达式中提取变量

时间:2018-05-03 05:03:02

标签: python string extraction

我想从布尔逻辑表达式中提取变量

离)
输入:E= A or B or (C and not D) -> String
输出:['E', 'A', 'B', 'C', 'D'] -> List

3 个答案:

答案 0 :(得分:0)

如果您的表达式和变量名称与示例建议的一样简单,则可能有效:

import re

string = 'E = A or B or (C and not D)'

variables = list(filter(None, re.split(r'[^A-Z]+', string)))

print(variables)

<强>输出

['E', 'A', 'B', 'C', 'D']

答案 1 :(得分:-1)

使用re(现在使用字符串输入):

inp = "E= random or andy"
#inp = "E= A or B or (C and not D)"

logic = ["xor","or","and","not","=",")","(",""," "]
outp = re.split(r'(=|\)|\(| )', inp)
outp = [x for x in outp if x not in logic ]

print(outp)

答案 2 :(得分:-2)

您可以在

中使用split()join()
s='E= A or B or (C and not D)'
s=''.join( c for c in s if  c not in '=()' )
l = []
for x in s.split():
    if(x not in ['or', 'and', not']):
        l.append(x)
print(l)

join()用于删除括号和=符号。

输出:

['E', 'A', 'B', 'C', 'D']