Python方程解析器

时间:2013-12-20 11:33:24

标签: python parsing tk equation

我正在编写一个程序,需要用户输入x的多项式函数。我正在使用Tkinter和python 2.5。

我有一个解析器方法,到目前为止,它采用输入的方程式并将其分解为术语而不会丢失符号。

我想学习每个术语并解析它以获得(系数,度数)的元组。例如,-2x ^ 3返回(-2,3)。然后我可以将它们添加到数组中并在程序中相应地操作它们。

是否有方法或标准模块可以做到这一点?

这是解析方法的开始。

def parse(a):
    termnum=[]
    terms=[]
    hi=[]
    num1=0
    num=0
    f=list(a)

    count=0
    negative=False
    coef=0.0
    deg=0.0
    codeg=[]
    for item in f:
        if (item=='-' or item=='+') and count!=0:
            termnum.append(count)
        count+=1
    for item in termnum:
        num1=num
        num=item
        current=''
        while num1<num:
            current=current+f[num1]
            num1+=1
        terms.append(current)
    num1=num
    num=len(f)
    current=''
    while num1<num:
        current=current+f[num1]
        num1+=1
    terms.append(current)
    print terms
parse('-x^2+3x+2x^3-x')

谢谢! P.S我不想使用外部包。

3 个答案:

答案 0 :(得分:1)

你可以使用正则表达式,

import re

test = '-x^2+3x+2x^3-x'

for m in re.finditer( r'(-{0,1}\d*)x\^{0,1}(-{0,1}\d*)', test ):
    coef, expn = list( map( lambda x: x if x != '' and x != '-' else x + '1' ,
                            m.groups( ) ))
    print ( 'coef:{}, exp:{}'.format( coef, expn ))

输出:

coef:-1, exp:2
coef:3, exp:1
coef:2, exp:3
coef:-1, exp:1

答案 1 :(得分:0)

寻找“递归下降解析器”。这是分析字符串的规范方法,其中涉及一些运算符优先级。

答案 2 :(得分:0)

看起来你正在用python和其他数学语言实现已经存在的东西。例如见:

http://www.gnu.org/software/octave/doc/interpreter/Solvers.html

http://stat.ethz.ch/R-manual/R-devel/library/base/html/solve.html

相关问题