【问题标题】:basic pyparsing : parsing expression using "and" and "or"基本 pyparsing :使用“and”和“or”解析表达式
【发布时间】:2016-10-13 22:35:33
【问题描述】:

我已经为 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”,而是使用任何既不包含“and”或“或”的可能字符串

我期待以下工作正常:

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

【问题讨论】:

  • 访问 pyparsing wiki 的示例页面,查看 SimpleBool.py 是如何完成的。 Pyparsing 不仅会进行原始解析,还会识别操作的优先级,A OR B AND C 实际上会解析为(A OR (B AND C))。这将大大简化您以后对该字符串的评估。另外,当我认为您的意思是 Literal 时,您使用的是 Word - 请不要使用前导和尾随空格,pyparsing 默认会跳过空格。

标签: python nested pyparsing


【解决方案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']]

【讨论】:

  • 它给了我“['c>5 or ', ['p==4 and c
  • 您期望得到哪个输出? ['c', '>', '5', 'or', ['p', '==', '4', 'and', 'c', '
  • 对不起,我没有说清楚。 ['c>5','or',['p==4','and','c
  • 哦,对不起。我打错了:字符串'r'不能包含空格。为方便起见,我已经编辑了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-14
  • 2014-05-13
  • 1970-01-01
相关资源
最近更新 更多