首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,Regex:不能从方程中获得系数

Python,Regex:不能从方程中获得系数
EN

Stack Overflow用户
提问于 2022-10-19 12:59:54
回答 1查看 27关注 0票数 0

我试图用正则表达式和后来的多重方程从这个方程中求出系数:

2a+3b=c

然而,我得到了这个恼人的错误。我检查了我的密码,一切对我来说都很好。这是一个错误:

代码语言:javascript
复制
AttributeError: 'int' object has no attribute 'group'

这是我的代码:

代码语言:javascript
复制
import re

all_coefficients = []

def equation_solver(*equations):
    for equation in equations:
        sides = equation.split('=')
        coefficients = []
        for side in sides:
            terms = re.split(r"\+", side)
            for term in terms:
                coefficient = re.match(r"\d", term)
                if coefficient == None:
                    coefficient = 1
                coefficients.append(int(coefficient.group(0)))
        all_coefficients.append(coefficients)


equations = []

while True:
    equations.append(input())
    if input() == 's':
        break

equation_solver(*equations)

提前感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-19 13:02:36

这会导致错误,因为re.match在术语c中找不到任何系数,所以如果它没有找到任何系数(仔细阅读),您将系数值指定为1,但现在不能使用group,因为现在系数是整数!!因此,在将其转换为整数之前使用group函数,它将如下所示:

代码语言:javascript
复制
import re

all_coefficients = []

def equation_solver(*equations):
    for equation in equations:
        sides = equation.split('=')
        coefficients = []
        for side in sides:
            terms = re.split(r"\+", side)
            for term in terms:
                coefficient = re.match(r"\d", term)
                if coefficient == None:
                    coefficient = 1
                else:
                    coefficient = coefficient.group(0) # Use group beforehand
                coefficients.append(int(coefficient))
        all_coefficients.append(coefficients)


equations = []

while True:
    equations.append(input())
    if input() == 's':
        break

equation_solver(*equations)

希望这能有所帮助

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74125767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档