gpt4 book ai didi

python - 使用 findall() 方法解析简单的数学方程

转载 作者:行者123 更新时间:2023-12-01 08:18:33 26 4
gpt4 key购买 nike

如何使用findall()方法解析数学方程?

例如,如果我有一个方程 8x >= 4 + 2y + 10z

这是我的编码

import re
equations = '8x >= 4 + 2y + 10z'
regexparse = r'\w+|[+/*-]'
result = re.findall(regexparse, equations)
print(result)

输出为

['8x', '4', '+', '2y', '+', '10z']

相反,我期望这个结果:

[('','8','x','>='),('','4','',''),('+','2','y',''),('+','10','z','')]

最佳答案

如果您希望 re.findall 返回 4 元组列表,则应该使用 4 个捕获组:

result = re.findall(r'(?=\S)([-+*/])?\s*(\d+)?\s*([a-z]+)?\s*([<>]?=)?', equations)

鉴于您的示例输入equations = '8x >= 4 + 2y + 10z'结果将变为:

[('', '8', 'x', '>='), ('', '4', '', ''), ('+', '2', 'y', ''), ('+', '10', 'z', '')]

关于python - 使用 findall() 方法解析简单的数学方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54836967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com