Ax**3+Bcos(x+y)+Cexp(-x**2)-bx+cy
怎么提取出。(系数与项之间有⭐,这里没显示出来)
A x3
B cos(x+y)
C exp(-x2)
-b x
c y
A x3
B cos(x+y)
C exp(-x2)
-b x
c y
下有代码,可直接复制使用。如有帮助,敬请采纳,你的采纳是我前进的动力,O(∩_∩)O谢谢!!!!!!!!
路过的朋友也可以点个赞~(≧▽≦)/~
测试公式
A*x**3+B*cos((x+y)+(x1*x-y**y1))+C*exp(-x**2)-b*x+c*y
A*x**3+B*cos((x+y)+(x1*x-y**y1))+C*x*exp(-x**2)-b*x+c*y*x
A*x**3+B*cos((x+y)+(x1*x-y**y1))+C*x*exp(-x**2)-b*x+c*y*x+A/B*x+B/A*y
不可完成:系数相同的表达式,有这方面的要求再增加
import re
representation1 = "A*x**3+B*cos(x+y)+C*exp(-x**2)-b*x+c*y"
representation1 = representation1.replace(' ','')
if representation1[0] not in '-+':
representation1 = '+' + representation1
representation2 = representation1.replace('**', '^')
# 去掉最短括号,防干扰
# representation3 = re.sub('\(.*?\)', '', representation2)
brackets_num_left = 0
brackets_num_right = 0
representation3 = representation1
replace = ''
for x in representation1:
if '(' in replace:
replace += x
if x == '(':
if replace == '':
replace = x
brackets_num_left += 1
if x == ')':
brackets_num_right += 1
if replace != '' and brackets_num_left == brackets_num_right:
representation3 = representation3.replace(replace, '')
replace = ''
# 获取系数
系数 = re.findall('[+\-].*?[A-Za-z]', representation3)
# 通过系数获取系数项
result = {}
result_str = ''
for x_i in range(len(系数)):
try:
res = re.findall(f'\{系数[x_i]}(.*?)\{系数[x_i + 1]}', representation1)
result[系数[x_i]] = res[0]
except:
result[系数[x_i]] = representation1.split(系数[-1])[-1]
result_str += 系数[x_i]+','+result[系数[x_i]]+','
print(result_str[:-1])
import re
F1 = "A*x**3+B*cos(x+y)+C*exp(-x**2)-b*x+c*y"
r = re.findall('(\(.*?\))', F1)
d = dict({str(i) *4: v for i, v in enumerate(r)}, **{"^^^^": "**","+-": "-"})
for k,v in d.items():
F1 = F1.replace(v, k)
r = F1.split("+")
res = sum([i.split("*") for i in r], [])
result = []
for i in res:
for k, v in d.items():
if i.find(k) > -1:
i = i.replace(k, v)
result.append(i)
print(result)
"""--result
['A', 'x**3', 'B', 'cos(x+y)', 'C', 'exp(-x**2)', '-b', 'x', 'c', 'y']
"""
系数与项之间有什么?
A x3,上面的x前有两个星号,也不要了?
你题目的解答代码如下:
import re
F1='A*x**3+B*cos(x+y)+C*exp(-x**2)-b*x+c*y'
li = re.findall(r'(\-?[a-zA-Z]+\(.+?\)|\-?(?:\*\*|[a-zA-Z0-9])+)\*(\-?[a-zA-Z]+\(.+?\)|\-?(?:\*\*|[a-zA-Z0-9])+)',F1)
for a,b in li:
print(a,b)
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!