Skip to main content
 首页 » 编程设计

python之基本的 pyparsing : parsing expression using "and" and "or"

2025年05月04日6虾米哥

我已经为获得 pyparsing 而奋斗了几个小时,即使我想做的是基本的。

我想解析基于“or”和“and”的表达式。

效果很好的例子:

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'] 

现在,我也会这样做,但不要使用“True”和“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'] 

请您参考如下方法:

我认为这个解决方案是合适的:

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']]