【问题标题】:python parse text in nested parentheses for n-ary treepython在n元树的嵌套括号中解析文本
【发布时间】:2020-10-09 10:39:58
【问题描述】:

我有这样的文字:

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

预期结果将是一个嵌套列表,以便创建文本的二叉树表示,因此:

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

我的尝试:

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)

我发现了很有趣的东西here

但是这个方法会返回一个char列表,​​我想加入单词(不是'a','b'而是'ab'),最重要的是我不明白的语法(以及函数)推送功能。

【问题讨论】:

  • 好的,所以我挖掘了这篇文章以寻找我使用 ast 找到的解决方案。目的是修改输入中给出的字符串,使其看起来像一个列表,然后使用 ast (ast.literal_eval(chain)) 对其进行评估。这是我的代码:

标签: python parsing nested


【解决方案1】:

正如评论中所说,这里我的解决方案可以适应任何类型的字符串。诀窍是将输入中给出的字符串转换为一个列表,然后使用 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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多