简体   繁体   中英

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) 

This works for your simple scenario if you don't want to include any non standard python libraries.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM