Python: determine if a string contains math?

前端 未结 3 1218
清酒与你
清酒与你 2021-01-23 11:46

Given these strings:

\"1 + 2\"
\"apple,pear\"

How can I use Python 3(.5) to determine that the first string contains a math problem and

3条回答
  •  粉色の甜心
    2021-01-23 12:16

    You can use a parsing library such as pyPEG, although there is room for improvment do more than this you could define a grammar like this:

    from pypeg2 import optional, List, Namespace
    import re
    
    number = re.compile(r'\d+')
    binop = re.compile(r'\+|\*') # Exercise: Extend to other binary operators
    
    
    class BinOp(Namespace):
        grammar = binop
    
    
    class Number(Namespace):
        grammar = number, optional("."), optional(number)
    
    
    class Expression(Namespace):
        grammar = Number, optional(BinOp, Number)
    
    
    class Equation(List):
        grammar = Expression, optional("="), optional(Expression)
    

    You can handle the error when an invalid expression is passed through and use the parse function to validate expressions:

    >>> import pypeg2
    >>> f = pypeg2.parse("3=3", Equation)
    >>> f = pypeg2.parse("3 = 3", Equation)
    >>> f = pypeg2.parse("3 + 3 = 3", Equation)
    >>> f = pypeg2.parse("3 * 3 = 3", Equation)
    >>> f = pypeg2.parse("3hi", Equation)
    Traceback (most recent call last):
      File "", line 1, in 
      File "/usr/local/lib/python3.5/site-packages/pypeg2/__init__.py", line 669, in parse
        raise parser.last_error
      File "", line 1
        3hi
         ^
    SyntaxError: expecting match on \d+
    

提交回复
热议问题