You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
fitt/newly_added/formula.py

103 lines
3.4 KiB

import re
def convert_log(expression):
# 匹配log(x,b)的正则表达式
pattern = r'log\((\w+),(\w+)\)'
match = re.match(pattern, expression)
if match:
x = match.group(1)
b = match.group(2)
# 构造新表达式
new_expression = f'(np.log({x}) + 1e-5) / (np.log({b}) + 1e-5)'
return new_expression
else:
return None
def convert_e(expression):
new_expression = 'np.exp'+expression[2:]
return new_expression
def convert_trigonometric(expression):
# 构造新表达式
new_expression = 'np.'+expression
return new_expression
def convert_x(expression):
# 匹配log(x,b)的正则表达式
pattern = r'(\w+)\^(\w+)'
match = re.match(pattern, expression)
if match:
base = match.group(1)
exponent = match.group(2)
# 构造新表达式
new_expression = f'np.power({base}, {exponent})'
return new_expression
else:
return None
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
def find_letter_index(string):
pattern = r'([a-zA-Z])x\b'
matches = re.findall(pattern, string)
# print(matches)
letter_indices = []
for i in range(len(string)):
if string[i] in matches:
if string[i+1]=='x':
letter_indices.append(i)
return letter_indices
def expression_output(expression):
# 示例使用
modified_list = find_letter_index(expression) # 将x前没有*的加上
index = 1
for i in modified_list:
expression = expression[0:index+i]+'*'+expression[index+i:]
index += 1
# print(expression)
expression = add_spaces(expression)
new_expression = remove_inner_spaces(expression)
list_expression = new_expression.split(' ')
conforms = ['e^', 'log', 'sin', 'cos', 'tan', '^']
new_list = []
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 ='x,'
for item in new_list:
if item not in parameter and item != 'x':
parameter = parameter+item+','
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
if len(parameter[:-1]) > 1:
return parameter[:-1], str_expression
else:
return None, None