如何标记字符串(其中包含有关数学计算和浮点数的数据)?

How to tokenize a string (which has data about mathematical calculations and floating point numbers)?

我正在尝试标记一个字符串(其中包含有关数学计算的数据)并创建一个列表。

例如,

a = "(3.43 + 2^2 / 4)"

function(a) => ['(', '3.43', '+', '2', '^', '2', '/', '4']

我不想使用外部导入(比如 nltk)。

我面临的问题是保持浮点数的完整性。

摸索了好几个小时,做了2个函数,遇到浮点数就出问题了

这是我所做的:

a = "(3.43 + 2^2 / 4)"
tokens = []

for x in range(1, len(a)-1):
no = []

if a[x] == ".":
    y = x
    no.append(".")

    while is_int(a[y-1]):
        no.insert(0, a[y-1])
        y -= 1

    y = x

    while is_int(a[y+1]):
        no.extend(a[y+1])
        y += 1

    token = "".join(no)
    no = []
    tokens.append(token)

else:
    tokens.append(a[x])

print(tokens)

输出:

['3', '3.43', '4', '3', ' ', '+', ' ', '2', '^', '2', ' ', '/', ' ', '4']

试试这个

a = "(3.43 + 2^2 / 4)"
tokens = []
no = ""

for x in range(0, len(a)):
    # Skip spaces
    if a[x] == " ":
        pass
    # Concatenate digits or '.' to number
    elif a[x].isdigit() or (a[x] == "."):
        no += a[x]
    # Other token: append number if any, and then token
    else:
        if no != "":
            tokens.append(no)
        tokens.append(a[x])
        no = ""

print(tokens)

输出:

['(', '3.43', '+', '2', '^', '2', '/', '4', ')']

注意,这不会处理超过一个字符的运算符,例如 ==、**、+=

另请注意,当表达式中的数字超过 1 位时,您的代码将不起作用。 但你可以试试这个:

a = "(3.43 + 22^222 / 4)"
list_a = a[1:-1].split()  # remove first and last paranthesis and split by expression
tokens = []
for val in list_a:
    if '.' in val:  # if number has '.' then convert it to float number.
        tokens.append(float(val))
    elif val.isdigit():  # if it is number then add it to tokens
        tokens.append(val)
    elif len(val)==1:  # if it is math expression then add it to tokens
        tokens.append(val)
    else:  # problem is when you have an expression like: "2^2" - we have to go char by char
        no = []
        for k in val:
            if k.isdigit():
                no.append(k)
            else:
                tokens.append(''.join(no))
                tokens.append(k)
                no = []
        tokens.append(''.join(no))

print(tokens)

您可以使用 Python 自己的分词器,它是标准 API 的一部分:

from tokenize import tokenize
from io import BytesIO

source = "(3.43 + 2^2 / 4)"
tokens = tokenize(BytesIO(source.encode('utf-8')).readline)
non_empty = [t for t in tokens if t.line != '']

for token in non_empty:
    print(token.string)

这将打印:

(
3.43
+
2
^
2
/
4
)

更多信息:https://docs.python.org/3/library/tokenize.html