def validate_text(text): try: BNF().parseString(text.replace('x', str(0)), parseAll=True) fn.evaluate_stack(fn.exprStack) print('validated') except fn.ParseException as pe: print(text, "failed parse:", str(pe)) return False except Exception as e: print(text, "failed eval:", str(e), fn.exprStack) return False return True
def calculate_y_values(x_values, expression): # Формирование значений оси у по функции expression = expression.replace('X', 'x') y_values = [] for x in x_values: fn.exprStack = [] try: BNF().parseString(expression.replace('x', str(x)), parseAll=True) x_value = fn.evaluate_stack(fn.exprStack) except fn.ParseException as pe: print(expression, "failed parse:", str(pe)) return 0 except Exception as e: print(expression, "failed eval:", str(e), fn.exprStack) return 0 y_values.append(x_value) return y_values
# op1 = evaluateStack( s ) # return opn[op]( op1, op2 ) # elif op == "PI": # return math.pi # 3.1415926535 # elif op == "E": # return math.e # 2.718281828 # elif op in fn: # return fn[op]( evaluateStack( s ) ) # elif op[0].isalpha(): # if op in variables: # return variables[op] # raise Exception("invalid identifier '%s'" % op) # else: # return float( op ) arithExpr = BNF() ident = Word(alphas, alphanums).setName("identifier") assignment = ident("varname") + '=' + arithExpr pattern = assignment | arithExpr if __name__ == '__main__': # input_string input_string = '' # Display instructions on how to quit the program print("Type in the string to be parsed or 'quit' to exit the program") input_string = input("> ") while input_string.strip().lower() != 'quit': if input_string.strip().lower() == 'debug': debug_flag = True