python разобрать текст во вложенных скобках для n-арного дерева - PullRequest
1 голос
/ 19 июня 2020

У меня есть такой текст:

Proxy='ab,cd(ef,gh),ij,kl(mn(op,kr),st),uv' 

Ожидаемым результатом будет вложенный список, чтобы создать представление текста в виде дерева в виде ничтожного дерева, поэтому:

ExpectedResult=['ab','cd',['ef','gh'],'ij','kl',['mn',['op','kr'],'st'],'uv']

My попробуйте:

temp=[]
stack=[]
comma=[]
op=[]
cl=[]
n=(len(test))

for idx in range(n):
    if test[idx] == ',' and not op and not cl and not comma:
        stack.append(test[0:idx])
        comma.append(idx)
    elif test[idx] == ',' and op and not cl and not comma:
        temp.append(test[op.pop()+1:idx])
        comma.append(idx)
    elif test[idx] == ',' and not op and cl and not comma:
        if len(test[cl[0]+1:idx]) > 1:
            stack.append(test[cl.pop()+1:idx])
            comma.append(idx)
        else:
            cl.pop()
            comma.append(idx)
    elif test[idx] == ',' and not op and not cl and comma:
        stack.append(test[comma.pop():idx])
        comma.append(idx)
    elif test[idx] == '(' and not op and not cl and comma:
        stack.append(test[comma.pop()+1:idx])
        op.append(idx)
    elif test[idx] == '(' and op and not cl and comma:
        temp.append(test[comma.pop()+1:idx])
        op.pop()
        op.append(idx)
    elif test[idx] == ')' and not op and not cl and comma:
        temp.append(test[comma.pop()+1:idx])
        stack.append(temp)
        temp=[]
        cl.append(idx)
    elif test[idx] == ')' and op and not cl and not comma:
        temp.append([test[op.pop()+1:idx]])
        cl.append(idx)
    elif test[idx] == ')' and not op and not cl and comma:
        temp.append(test[comma.pop()+1:idx])
        stack.append(temp)
        temp=[]
        cl.append(idx)

Я нашел очень интересные вещи здесь

Но этот метод вернет список символов, и я хочу соединить слова (не 'a' , 'b', но 'ab'), и больше всего я не понимаю синтаксис (и, следовательно, функцию) функции pu sh.

1 Ответ

0 голосов
/ 02 июля 2020

Как сказано в комментарии, вот мое решение, которое можно адаптировать к любому типу строки. Хитрость заключается в том, чтобы преобразовать строку, указанную во входных данных, в виде списка, а затем использовать ast для эффективного преобразования ее в список.

def parenthesesParser(string):
    ref=[]
    string=re.sub('\.','',string)
    string=string.rstrip(', ')
    for char in string:
        if char == '(':
            ref.append('\',[\'')
        elif char == ')':
            ref.append('\']')
        elif char == ',':
            ref.append('\',\'')
        elif char == '.':
            ref.append('\',\'')
        else:
            ref.append(char)
    ref='\''+''.join(ref)+'\''
    ref=re.sub('\'\'','\'',ref)
    ref=re.sub(']\'',']',ref)
   return ast.literal_eval(ref.strip())
...