我正在搜索一个可以进行布尔运算的库并找到了 sympy。我编写了以下程序并执行布尔运算。我有例外。
import itertools
import sympy
data = ['iq,next_state=((!SE&D&RS)|(SE&SI)))']
data_1 = data[0].split(',')
for item in data_1:
if item.find('next_state=')!= -1:
item_list = item.split('=')
item_op = item_list[len(item_list) -1].lstrip('(').rstrip(')')
item_list = item_list[len(item_list) -1].replace('(','').replace(')','')
item_list = item_list.replace("&",",").replace("|",",").replace("!","")
item_list = item_list.split(',')
item_list = list(set(item_list))
print item_list
item_op = "(" + item_op + ")"
print "item-op",item_op
list_exp = item_op.split('|')
#print list_exp
expr = sympy.sympify(item_op)
variables = sorted(expr.free_symbols)
for truth_values in sympy.cartes([0, 1], repeat=len(item_list)):
values = dict(zip(variables, truth_values))
print sorted(values.items()), expr.subs(values)
错误:
['SI', 'D', 'SE', 'RS'] #Need to truth table for 4 element
item-op (!SE&D&RS)|(SE&SI) #This operation need to perform
Traceback (most recent call last):
File "next_state.py", line 21, in <module>
expr = sympy.sympify(item_op)
File "/.local/lib/python2.7/site-packages/sympy/core/sympify.py", line 297, in sympify
raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse u'(!SE&D&RS)|(SE&SI)'' failed, because of exception being raised:
TokenError: