簡體   English   中英

Python:從字符串中提取數學方程或表達式

[英]Python: Extract math equations or expressions from string

我有多個輸入文件,其中包含一個問題列表,其中包括幾個數學問題,我試圖只提取數學方程

示例輸入文件:

  1. 計算以下方程 y = mx + c,其中 m 是斜率,c 是截距
  2. 重新排列以下內容:溢出堆棧
  3. 如果 2^3 = 2x,則求 x
  4. 如果 {(2x+3)* (23x+3)} = 256,則求 x

期望的輸出:

  1. y = mx + c
  2. 不適用
  3. 2^3 = 2x
  4. {(2x+3)* (23x+3)} = 256

到目前為止,我已經嘗試使用正則表達式來解析“=”並分別提取左側和右側部分,但它確實遇到了錯誤(尤其是最后一個)

由於數學以多種不同的模式呈現,我將通過創建一個數學模式元組來解決這個問題。

首先將每一行分成自己的字符串,然后制作一個模式,從中提取您想要的內容。 然后將進行提取的模式添加到元組中。 我在下面做了一個簡單的例子。 我做的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM