jeudi 30 juin 2016

Parsing a symbolic equation in Python


I'm new to Python and find myself in the following situation. I work with equations stored as strings, such as:

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

I'm looking to parse the string and store the numeric and alphabetic parts separately in two lists, or some other container. A (very) rough sketch of what I'm trying to put together would look like:

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

Any resources/references/pointers would be much appreciated.

Thanks!

Update

Here's one solution I came up with that's probably overly-complicated but seems to work. Thanks again to all those responded!

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) 

Aucun commentaire:

Enregistrer un commentaire