我有多个输入文件,其中有一个问题列表,其中包括一些数学问题,我试图只提取数学方程
示例输入文件:
- 计算以下方程y=mx+c,其中m为斜率,c为截距
- 重新排列以下内容:溢出堆栈
- 如果2^3=2x,则查找x
- 如果{(2x+3(*(23x+3(}=256,则查找x
所需输出:
- y=mx+c
- NA
- 2^3=2x
- {(2x+3(*(23x+3(}=256
到目前为止,我已经尝试过regex来解析"="并分别提取左侧和右侧部分,但它确实遇到了错误(尤其是最后一个(
由于数学以许多不同的模式表示,我会通过创建数学模式的元组来实现这一点。
首先,将每一行分隔成自己的字符串,并创建一个模式,从中提取您想要的内容。然后将进行提取的模式添加到元组中。我在下面做了一个简单的例子。我做的for循环不是最好的,但应该足够好地证明解决方案:
import re
t1 = 'Evaluate the following equation y = mx + c, where m is slope and c is intercept'
t2 = 'Rearrange the following: overflow stack'
t3 = 'Find x if 2^3 = 2x'
t4 = 'Find x if {(2x+3)* (23x+3)} = 256'
math_patterns = (r'((y|x)s*=s*.+),', r'ifs(.+)', r'({.+)')
for pattern in math_patterns:
if re.search(pattern, t1):
print(re.search(pattern, t1).group(1))
continue
if re.search(pattern, t3):
print(re.search(pattern, t3).group(1))
continue
if re.search(pattern, t4):
print(re.search(pattern, t4).group(1))
continue
将输出以下内容:
y = mx + c
2^3 = 2x
{(2x+3)* (23x+3)} = 256