基础的pyparsing:使用“与”和“或”解析表达式

3 投票
1 回答
726 浏览
提问于 2025-04-18 03:35

我花了好几个小时在搞pyparsing,尽管我想做的事情其实很简单。

我想解析基于“或”和“与”的表达式。

下面是一个运行得很好的例子:

s = "((True and True) or (False and (True or False)) or False)"
parens = pyparsing.nestedExpr( '(', ')', content=pyparsing.Word(pyparsing.alphanums) | ' or ' | " and " )
r = parens.parseString(s)[0]
print parens.parseString(s)[0]

这个例子输出:

[['True', 'and', 'True'], 'or', ['False', 'and', ['True', 'or', 'False']], 'or', 'False']

现在,我想做同样的事情,但不想用“真”和“假”,而是用任何不包含“和”或“或”的字符串。

我原本以为下面的代码可以正常工作:

s = "( c>5 or (p==4 and c<4) )"
parens = pyparsing.nestedExpr( '(', ')', content=pyparsing.Word(' or ') | ' and ' )
print parens.parseString(s)[0]

但是这段代码抛出了一个异常:

pyparsing.ParseException: Expected ")" (at char 2), (line:1, col:3)

我尝试了很多,主要是想改变内容,但都没有成功。

有没有什么想法?

---- 注意

我最后还是用了自己的代码,而不是pyparsing。 不过我想这个问题对那些仍然对pyparsing感兴趣的人来说还是有意义的。

这是我现在使用的代码:

def parse(s,container):
    my_array = []
    i = 0
    while i < len(s):
        if s[i]!="(" and s[i]!=")":
            my_array.append(s[i])
            i+=1 
        elif s[i]=="(" :
            end_index = parse(s[i+1:],my_array)
            i += end_index+1
        elif s[i]==")":
            container.append(my_array)
            return i+1
    return my_array

例子:

s = "(True and True) or (False and (True or False)) or False"
to_broaden = ("(",")")
for tb in to_broaden : s = s.replace(tb," "+tb+" ")
s = s.split()
print parse(s,[])

结果:

[['True', 'and', 'True'], 'or', ['False', 'and', ['True', 'or', 'False']], 'or', 'False']

1 个回答

1

我觉得这个解决方案是合适的:

s = "( c>5 or (p==4 and c<4) )"

#It's pyparsing.printables without ()
r = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'*+,-./:;<=>?@[\]^_`{|}~'
parens = pyparsing.nestedExpr( '(', ')',  content=pyparsing.Word(r))
res = parens.parseString(s)[0].asList()
print res#['c>5', 'or', ['p==4', 'and', 'c<4']]

撰写回答