1

Имею задачу: Распарсить строку (просто пример):

'6.6/2.2*(1-0.5)'

в:

['6.6', '/', '2.2', '*', ['1', '-', '0.5']]

Знаю, что это можно сделать каким то образом с помощью pyparsing.Forward.parseString, но как, понять не могу. Как работать с этим методом, что передавать, как вызывать? Подскажите, пожалуйста.

1

1 ответ 1

0

Можно так:

S = '6.6/2.2*(1-0.5)'

signs = ['/', '+', '*', '-', '(', ')']

def pars_expr(S):
    IN = False
    IN_OPTS = False

    res = []
    tmp = []
    opt = []

    for i, item in enumerate(S):

        if item == '(':
            IN_OPTS = True
            continue

        if not IN_OPTS:
            if item not in signs:
                IN = True

            if IN and item not in signs:
                tmp.append(item)
                if i == len(S)-1:
                    res.append(''.join(tmp))
            if IN and item in signs:
                IN = False
                res.append(''.join(tmp))
                tmp = []

            if not IN and item in signs:
                res.append(item)
        else:

            if item not in signs:
                IN = True

            if IN and item not in signs:
                tmp.append(item)
            if IN and item in signs:
                IN = False
                opt.append(''.join(tmp))
                tmp = []

            if item == ')':
                IN_OPTS = False
                res.append(opt)
                opt = []
                continue

            if not IN and item in signs:
                opt.append(item)


    return res


print(pars_expr(S))

Это если не хотите пользоваться библиотеками

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.