簡體   English   中英

基本的pyparsing:使用“ and”和“ or”解析表達式

[英]basic pyparsing : parsing expression using “and” and “or”

即使我想做的是基本操作,我也一直在努力爭取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']

現在,我將保持不變,但是使用任何不包含“和”或“或”的可能字符串代替“ 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']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM