如何在python中拆分一串数学表达式? [英] How can I split a string of a mathematical expressions in python?
问题描述
我制作了一个程序,可以在 python 中将中缀转换为后缀.问题是当我引入论点时.如果我引入这样的东西:(这将是一个字符串)
I made a program which convert infix to postfix in python. The problem is when I introduce the arguments. If i introduce something like this: (this will be a string)
( ( 73 + ( ( 34 - 72 ) / ( 33 - 3 ) ) ) + ( 56 + ( 95 - 28 ) ) )
它将用 .split() 拆分它,程序将正常运行.但我希望用户能够介绍这样的东西:
it will split it with .split() and the program will work correctly. But I want the user to be able to introduce something like this:
((73 + ( (34- 72 ) / ( 33 -3) )) + (56 +(95 - 28) ) )
如您所见,我希望空格可以是微不足道的,但程序会继续按括号、整数(不是数字)和操作数拆分字符串.
As you can see I want that the blank spaces can be trivial but the program continue splitting the string by parentheses, integers (not digits) and operands.
我尝试用 for
来解决它,但我不知道如何捕捉整数 (73 , 34 ,72) 而不是一个数字一个数字 (7, 3 , 3 , 4, 7 , 2)
I try to solve it with a for
but I don't know how to catch the whole number (73 , 34 ,72) instead one digit by digit (7, 3 , 3 , 4 , 7 , 2)
总而言之,我想要的是将像 ((81 * 6)/42+ (3-1))
这样的字符串拆分为:
To sum up, what I want is split a string like ((81 * 6) /42+ (3-1))
into:
[(, (, 81, *, 6, ), /, 42, +, (, 3, -, 1, ), )]
推荐答案
Tree with ast
您可以使用 ast
来获得表达式树:
Tree with ast
You could use ast
to get a tree of the expression :
import ast
source = '((81 * 6) /42+ (3-1))'
node = ast.parse(source)
def show_children(node, level=0):
if isinstance(node, ast.Num):
print(' ' * level + str(node.n))
else:
print(' ' * level + str(node))
for child in ast.iter_child_nodes(node):
show_children(child, level+1)
show_children(node)
它输出:
<_ast.Module object at 0x7f56abbc5490>
<_ast.Expr object at 0x7f56abbc5350>
<_ast.BinOp object at 0x7f56abbc5450>
<_ast.BinOp object at 0x7f56abbc5390>
<_ast.BinOp object at 0x7f56abb57cd0>
81
<_ast.Mult object at 0x7f56abbd0dd0>
6
<_ast.Div object at 0x7f56abbd0e50>
42
<_ast.Add object at 0x7f56abbd0cd0>
<_ast.BinOp object at 0x7f56abb57dd0>
3
<_ast.Sub object at 0x7f56abbd0d50>
1
正如@user2357112 在评论中所写:ast.parse
解释 Python 语法,而不是数学表达式.(1+2)(3+4)
将被解析为函数调用,并且列表推导式将被接受,即使它们可能不应被视为有效的数学表达式.
As @user2357112 wrote in the comments : ast.parse
interprets Python syntax, not mathematical expressions. (1+2)(3+4)
would be parsed as a function call and list comprehensions would be accepted even though they probably shouldn't be considered a valid mathematical expression.
如果你想要一个扁平的结构,正则表达式可以工作:
If you want a flat structure, a regex could work :
import re
number_or_symbol = re.compile('(\d+|[^ 0-9])')
print(re.findall(number_or_symbol, source))
# ['(', '(', '81', '*', '6', ')', '/', '42', '+', '(', '3', '-', '1', ')', ')']
它寻找:
- 多位数字
- 或任何不是数字或空格的字符
获得元素列表后,您可以检查语法是否正确,例如使用 stack
来检查括号是否匹配,或者每个元素是否都是已知的.
Once you have a list of elements, you could check if the syntax is correct, for example with a stack
to check if parentheses are matching, or if every element is a known one.
这篇关于如何在python中拆分一串数学表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!