You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python正则表达式问题:无法从方程中提取系数

问题分析与解决

错误原因

报错AttributeError: 'int' object has no attribute 'group'的直接原因是:当re.match(r"\d", term)匹配不到数字时(比如term是c),你将coefficient赋值为整数1,但后续代码依然执行coefficient.group(0)——整数类型没有group方法,因此触发错误。

修复后的代码

import re

all_coefficients = []

def equation_solver(*equations):
    for equation in equations:
        sides = equation.split('=')
        coefficients = []
        for side in sides:
            # 处理加减号,将减号替换成+(-),统一按+分割
            processed_side = side.replace('-', '+-')
            terms = [t for t in processed_side.split('+') if t]  # 过滤空字符串
            for term in terms:
                # 匹配开头的正负号+数字,没有数字则视为1或-1
                match = re.match(r"([+-]?)(\d*)", term)
                sign_part = match.group(1)
                num_part = match.group(2)
                
                if not num_part:
                    # 没有数字,系数是1或-1
                    coeff = -1 if sign_part == '-' else 1
                else:
                    coeff = int(sign_part + num_part) if sign_part else int(num_part)
                
                coefficients.append(coeff)
        all_coefficients.append(coefficients)

# 修正输入循环逻辑:读取每一行,直到输入's'为止
equations = []
while True:
    line = input().strip()
    if line == 's':
        break
    if line:  # 忽略空行
        equations.append(line)

equation_solver(*equations)
# 打印查看结果
print(all_coefficients)

关键改进点

  1. 修复核心错误:将匹配结果和默认值的逻辑分离,避免对整数调用group方法。
  2. 支持负数项:通过替换-为+-,统一处理加减项,避免拆分后出现带负号的项无法正确匹配。
  3. 完善系数匹配:
    • 匹配正负号(如-3b中的-)
    • 处理无数字的变量(如c对应系数1,-c对应系数-1)
  4. 修正输入循环:原代码会额外读取一行作为终止判断,导致输入逻辑混乱,现在改为读取每行内容,若为s则终止,否则加入方程列表。

测试示例

输入:

2a+3b=c
3a-4b=5
s

输出:

[[2, 3, 1], [3, -4, 5]]

内容的提问来源于stack exchange,提问作者ss3387

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:25:19