Ich hab mir gestern Abend mal überlegt einen simplen Parser für mathematische Ausdrücke zu schreiben. Ich weiß daß es da schon diverse fertige gibt, mir geht es aber im wesentlichen um den Lerneffekt und nicht darum, das Ding irgendwie zu benutzen.
Das erste Problem auf das ich dabei gestoßen bin ist den Ausdruck in sinnvolle "Päckchen" zu zerlegen. Mein erster Versuch war es das irgendwie mit regular expressions zu machen. An der Stelle hat mich die Doku aber mehr verwirrt als geholfen.
Ich hab mir jetzt ne Funktion zusammengebaut die über alle Zeichen des Ausdrucks iteriert und dann an beliebigen Zeichen trennt:
Code: Alles auswählen
def splitExpression(string, characters):
""" splits a string by a sequence of characters """
# convert the given expression into a list
stringList = list(expression)
# a container for the output
output = ["["]
""" remark:
the expression must start with a spliting character.
Therefore the first character of the output string is set to a opening square bracket
Furthermore the set af splitting characters is extended by a square bracket. """
# iterate over each character
for char in stringList:
# if actual character is a splitter append list
if char in characters:
output.append(char)
# if actual character is not a splitter, check the prior one
else:
# if the prior character is a splitter, append list
if output[len(output)-1] in characters:
output.append(char)
# if not, join the strings
else:
output[len(output)-1] += char
# Finaly the output ends with a closing square bracket
output.append("]")
return output
Code: Alles auswählen
expression = "11+5/(548+6)-sin(8)"
splitter = ["+", "-", "(", ")","/", "*" ]
result = splitExpression(expression, splitter)
print result
>>>
['[', '11', '+', '5', '/', '(', '548', '+', '6', ')', '-', 'sin', '(', '8', ')', ']']
Mag mir vieleicht grad mal jemand zeigen wie das mit den regex richtig gemacht wird?
Gruß Arzhur Dent