肖先志 2022-07-22 10:43 采纳率: 100%
浏览 93
已结题

一个表达式怎么提取出系数和选项。(语言-python)

Ax**3+Bcos(x+y)+Cexp(-x**2)-bx+cy
怎么提取出。(系数与项之间有⭐
,这里没显示出来)
A x3
B cos(x+y)
C exp(-x
2)
-b x
c y
A x3
B cos(x+y)
C exp(-x
2)
-b x
c y

img

  • 写回答

4条回答 默认 最新

  • 脚踏南山 2022-07-22 11:07
    关注

    下有代码,可直接复制使用。如有帮助,敬请采纳,你的采纳是我前进的动力,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])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 7月30日
  • 已采纳回答 7月22日
  • 修改了问题 7月22日
  • 修改了问题 7月22日
  • 展开全部

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?