【问题标题】:Splitting a math expression string into tokens in Python在 Python 中将数学表达式字符串拆分为标记
【发布时间】:2014-07-25 09:40:45
【问题描述】:

我有很多 python 字符串,例如"A7*4""Z3+8""B6 / 11",我想拆分这些字符串以便它们出现在一个列表中,格式为["A7", "*", "4"]["B6", "/", "11"]等。我使用了很多不同的拆分方法,但我认为我只需要在有数学符号的地方执行拆分,例如/,*,+,-。我还需要去掉空格。

目前我正在使用代码re.split(r'(\D)', "B6 / 11"),它返回['', 'B', '6', ' ', '', '/', '', ' ', '11']。相反,我想找回["B6", "/", "11"]

【问题讨论】:

  • 总是只有三个部分,$operand1 $operation $operand2
  • @Pavel 在这一点上只是三个部分。

标签: python regex string split


【解决方案1】:

从字符串中删除空格后,您应该在 character set [+-/*] 上拆分:

>>> import re
>>> def mysplit(mystr):
...     return re.split("([+-/*])", mystr.replace(" ", ""))
...
>>> mysplit("A7*4")
['A7', '*', '4']
>>> mysplit("Z3+8")
['Z3', '+', '8']
>>> mysplit("B6 / 11")
['B6', '/', '11']
>>>

【讨论】:

  • 6*-7 怎么样?
【解决方案2】:

有一种方法可以在不使用正则表达式的情况下使用 Python tokenizer 来解决这个问题。我使用了一个更复杂的公式来展示这个解决方案的功能。

from io import StringIO
import tokenize

formula = "(A7*4) - (Z3+8) -  ( B6 / 11)"
print([token[1] for token in tokenize.generate_tokens(StringIO(formula).readline) if token[1]])

结果:

['(', 'A7', '*', '4', ')', '-', '(', 'Z3', '+', '8', ')', '-', '(', 'B6', '/', '11', ')']

【讨论】:

  • 在 python 2.7.13 上,上面的例子抛出了一个错误。 TypeError: initial_value must be unicode or None, not str 。需要在公式 var 字符串前面添加 'u' 标志。
猜你喜欢
  • 2017-09-09
  • 2013-09-15
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
相关资源
最近更新 更多