【问题标题】:Tokenize math expressions without importing any module in python标记数学表达式而不在 python 中导入任何模块
【发布时间】:2021-05-24 16:20:21
【问题描述】:

我正在尝试使用运算符和括号对数学表达式进行标记,包括整数、浮点数(正数和负数)。

例如,

expression = "-2.56*13.2+(11/-4)-.55"
tokenize(expression)
["-2.56", "*", "13.2", "+", "(", "11", "/", "-4", ")", "-", ".55"]

我的尝试:

def tokenize(expression):
    tokens = []
    for char in expression:
    if char.isdigit() and tokens[-1].isdigit():
        tokens[-1] += char
    else:
        tokens.append(char)
    return tokens

expression2 = "((12+13)*5)"
tokenize(expression2)
['(', '(', '12', '+', '13', ')', '*', '5', ')']

我的代码适用于以括号开头的表达式,但不适用于不是括号的表达式,也不适用于负号和浮点数。在不导入任何模块的情况下,我应该如何用正负浮点数标记表达式?任何帮助将不胜感激!

【问题讨论】:

  • 请修正代码的缩进
  • 如果没有re 模块,这是一个非常难以解决的问题(并且使用为实际语言解析而设计的东西会更好)。特别是减号的模糊性使得它比简单地确定如何对每个单独的字符进行分类要复杂得多。为什么“不导入任何模块”要求?如果是为了一门课程,他们太早把你扔进了深渊,我建议放弃它,找一门更适合初学者的课程。

标签: python token tokenize


【解决方案1】:

你可以建立一个简单的表格,可以根据输入的字符和前面的字符来决定是返回当前的字符表达式,还是继续累积字符:

d = {'-':[lambda x:x.isdigit() or x == ')', lambda x:x.isdigit() or x == '('], '(':True, ')':True, '*':[lambda x:x.isdigit() or x == ')', lambda x:x.isdigit() or x == '('], '+':[lambda x:x.isdigit() or x == ')', lambda x:x.isdigit() or x == '('], '/':[lambda x:x.isdigit() or x == ')', lambda x:x.isdigit() or x in ['-', '(']]}
def tokenize(s):
   l, r = None, None
   while s:
      t, s = s[0], s[1:]
      if t not in d:
         r, l = t if r is None else r+t, t
      else:
         if (f:=isinstance(d[t], list)) and not s: #need lookahead, but have reached eof
            raise Exception('tokenization error')
         if (f and l and d[t][0](l) and d[t][1](s[0])) or (not f and d[t]):
            yield r
            yield t
            r, l = None, t
         else:
            r, l = t if r is None else r + t, t     
   if r is not None:
       yield r

exprs = ["-2.56*13.2+(11/-4)-.55", "((12+13)*5)", '-3', '(-1.4)', '(4/5)*4+(-1)*(4+(3-2))']
r = [list(filter(None, tokenize(i))) for i in exprs]

输出:

[['-2.56', '*', '13.2', '+', '(', '11', '/', '-4', ')', '-.55'], ['(', '(', '12', '+', '13', ')', '*', '5', ')'], ['-3'], ['(', '-1.4', ')'], ['(', '4', '/', '5', ')', '*', '4', '+', '(', '-1', ')', '*', '(', '4', '+', '(', '3', '-', '2', ')', ')']]

【讨论】:

  • 谢谢你的回答。如问题所述,我不允许进口任何东西。如果允许我这样做,事情会容易得多......
猜你喜欢
  • 1970-01-01
  • 2019-03-22
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 2019-11-10
  • 2013-01-09
相关资源
最近更新 更多