本文介绍了Python:确定字符串是否包含数学?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下字符串:
"1 + 2"
"apple,pear"
如何使用Python 3(.5)确定第一个字符串包含数学问题,并且没有其他内容,而第二个字符串不包含数学问题?
How can I use Python 3(.5) to determine that the first string contains a math problem and nothing else and that the second string does not?
推荐答案
这是一种实现方法:
import ast
UNARY_OPS = (ast.UAdd, ast.USub)
BINARY_OPS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod)
def is_arithmetic(s):
def _is_arithmetic(node):
if isinstance(node, ast.Num):
return True
elif isinstance(node, ast.Expression):
return _is_arithmetic(node.body)
elif isinstance(node, ast.UnaryOp):
valid_op = isinstance(node.op, UNARY_OPS)
return valid_op and _is_arithmetic(node.operand)
elif isinstance(node, ast.BinOp):
valid_op = isinstance(node.op, BINARY_OPS)
return valid_op and _is_arithmetic(node.left) and _is_arithmetic(node.right)
else:
raise ValueError('Unsupported type {}'.format(node))
try:
return _is_arithmetic(ast.parse(s, mode='eval'))
except (SyntaxError, ValueError):
return False
这篇关于Python:确定字符串是否包含数学?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!