在 python 中解析/重新格式化标记化列表

问题描述 投票:0回答:0

我有表格的令牌列表 “(a 或 b)和 c 或 d 和 c” 或者 “(a 或 b)和 c 或(d 和 c)”

我想将这些标记重新格式化为以下形式的字符串: 表达式具有任意形式,如 (a 或 b) 和 c 或 (d 和 c)。

编写 python 将表达式重新格式化为: {{or {and {or a b} c} {and d c}}}

我的代码适用于某些令牌列表,但不适用于其他列表:

def parse_expression(tokens):

    if len(tokens) == 1:
        return tokens[0]
    
    # Find the top-level operator (either 'and' or 'or')
    parens = 0
    for i in range(len(tokens) - 1, -1, -1):
        token = tokens[i]
        if token == ')':
            parens += 1
        elif token == '(':
            parens -= 1
        elif parens == 0 and token in {'AND', 'OR'}:
            op = token
            break
    else:
        print('Invalid expression')
    
    # Recursively parse the sub-expressions
    left_tokens = tokens[:i]
    right_tokens = tokens[i+1:]
    print("{i} left {left_tokens}")
    print("{i} right {right_tokens}")
    if op == 'AND':
        left = parse_expression(left_tokens)
        right = parse_expression(right_tokens)
        return f'(and {left} {right})'
    else:
        left = parse_expression(left_tokens)
        right = parse_expression(right_tokens)
        return f'(or {left} {right})'
        

x=list()
x = ['x', 'AND', 'y', 'AND', 'z', 'AND', '(', '(', 'a', 'AND', 'b', ')', 'OR', '(', 'c', 'AND', 'd', ')', ')']
y = ['x', 'AND', 'y', 'AND', 'z', 'AND', '(', 'w', 'AND', 'q', ')']

它似乎没有括号就可以工作,但当我使用它们时却不行。

当我尝试用解析器重新格式化这些时,我不断得到

Traceback (most recent call last):
  File "./prog.py", line 41, in <module>
  File "./prog.py", line 29, in parse_expression
  File "./prog.py", line 27, in parse_expression
UnboundLocalError: local variable 'op' referenced before assignment

我做错了什么?

python parsing boolean expression reformatting
© www.soinside.com 2019 - 2024. All rights reserved.