在Python中解析符号方程

时间:2016-06-21 21:34:33

标签: python

我是Python新手,发现自己处于以下情况。我使用存储为字符串的方程式,例如:

>>> my_eqn = "A + 3.1B - 4.7D"

我希望解析字符串并将数字和字母部分分别存储在两个列表或其他容器中。一个(非常)粗略的草图,我试图放在一起看起来像:

>>> foo = parse_and_separate(my_eqn);
>>> foo.numbers
    [1.0, 3.1, -4.7]
>>> foo.letters
    ['A', 'B', 'D']

非常感谢任何资源/参考/指针。

谢谢!

更新

我提出的一个解决方案可能过于复杂,但似乎有效。再次感谢所有回复者!

import re                                                                                                                                               my_eqn = "A + 3.1B - 4.7D"                                                  

# add a "1.0" in front of single letters                                          
my_eqn = re.sub(r"(\b[A-Z]\b)","1"+ r"\1", my_eqn, re.I)                    

# store the coefficients and variable names separately via regex                      
variables = re.findall("[a-z]", my_eqn, re.I)                               
coeffs = re.findall("[-+]?\s?\d*\.\d+|\d+", my_eqn)                         

# strip out '+' characters and white space                                  
coeffs = [s.strip('+') for s in coeffs]                                     
coeffs = [s.replace(' ', '') for s in coeffs]                               

# coefficients should be floats                                
coeffs = list(map(float, coeffs))                                           

# confirm answers                                                           
print(variables)                                                            
print(coeffs) 

1 个答案:

答案 0 :(得分:1)

如果你不想包含任何非标准的python库,这适用于你的简单场景。

class Foo:
    def __init__(self):
        self.numbers = []
        self.letters = []

def split_symbol(symbol, operator):
    name = ''
    multiplier = ''
    for letter in symbol:
        if letter.isalpha():
            name += letter
        else:
         multiplier += letter
    if not multiplier:
        multiplier = '1.0'
    if operator == '-':
        multiplier = operator + multiplier
    return name, float(multiplier) 

def parse_and_separate(my_eqn):
    foo = Foo()
    equation = my_eqn.split()
    operator = ''
    for symbol in equation:
        if symbol in ['-', '+']:
            operator = symbol
        else:
            letter, number = split_symbol(symbol, operator)
            foo.numbers.append(number)
            foo.letters.append(letter)
    return foo

foo = parse_and_separate("A + 3.1B - 4.7D + 45alpha")
print(foo.numbers)
print(foo.letters)