[英]Python: Extract math equations or expressions from string
我有多個輸入文件,其中包含一個問題列表,其中包括幾個數學問題,我試圖只提取數學方程
示例輸入文件:
期望的輸出:
到目前為止,我已經嘗試使用正則表達式來解析“=”並分別提取左側和右側部分,但它確實遇到了錯誤(尤其是最后一個)
由於數學以多種不同的模式呈現,我將通過創建一個數學模式元組來解決這個問題。
首先將每一行分成自己的字符串,然后制作一個模式,從中提取您想要的內容。 然后將進行提取的模式添加到元組中。 我在下面做了一個簡單的例子。 我做的 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'if\s(.+)', 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.