# import re # # def add_spaces(expression): # # 匹配运算符的正则表达式 # pattern = r'([+\-*/])' # # 替换匹配到的运算符 # new_expression = re.sub(pattern, r' \1 ', expression) # return new_expression # # # 示例用法 # expression = 'a+b^c-c*d/e' # new_expression = add_spaces(expression) # print(new_expression) import re from formula import * def remove_inner_spaces(expression): # 匹配括号内的空格的正则表达式 pattern = r'\((.*?)\)' # 替换匹配到的括号内的空格 new_expression = re.sub(pattern, lambda match: '(' + match.group(1).replace(' ', '') + ')', expression) return new_expression def add_spaces(expression): # 匹配运算符的正则表达式 pattern = r'([+\-*/])' # 替换匹配到的运算符 new_expression = re.sub(pattern, r' \1 ', expression) return new_expression # 示例用法 expression = 'a+b^c-c*d/e+sin(x+y)+e^(0.2*x)' expression = add_spaces(expression) new_expression = remove_inner_spaces(expression) list_expression = new_expression.split(' ') conforms = ['e^', 'log', 'sin', 'cos', 'tan', '^'] new_list = [] # result2 = ' '.join([word for word in expression.split() if not any(word.startswith(s) for s in conforms)]) # print(result2) # letters = [char for char in result2 if char.isalpha()] # print(letters) for expres in list_expression: new_list.append(expres) for i in range(6): if conforms[i] in expres: index = list_expression.index(expres) if i == 0: list_expression[index] = convert_e(expres) elif i==1: list_expression[index] = convert_log(expres) elif i==5: list_expression[index] = convert_x(expres) else: list_expression[index] = convert_trigonometric(expres) new_list[-1] = new_list[-1].replace(conforms[i], "") break new_list = [char for item in new_list for char in item if char.isalpha()] parameter ='' for item in new_list: if item not in parameter: parameter = parameter+item+',' print(parameter[:-1]) for item in new_list: if item not in parameter: parameter = parameter+item+',' str_expression = '' for item in list_expression: str_expression = str_expression + item print(str_expression[:-1]) print(list_expression)