如何在括号内使用PLY处理STRING表达式之间的OR运算符

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

我想解释如下句子:

 "i + want + to + turn + ( on | off ) + the + lights"

获得类似的句子:

  "i want to turn on the lights"

  "i want to turn off the lights"

我尝试定义一个词法分析器和解析器来帮助我解决这个问题,但是我不知道如何处理括号之间的表达式和“ OR”运算符,它们给出类似有效值的一个或另一个表达式管道(|)字符。

在STRING的情况下,语法规则'+'(加号)是连续操作。

def p_expression_plus(p):
     'expression : expression PLUS term'
     p[0] = p[1] + ' ' + p[3]

但是我不知道如何定义OR操作,并像上面定义的那样以单独的方式获得括号之间两个字符串的相加。

任何想法都会受到赞赏。谢谢!

parsing yacc lex lexer ply
1个回答
0
投票

我认为这不是一个真正的解析问题,因为解析您的表达式很简单。尽管您没有展示自己的尝试,但是您展示的内容足以表明您知道该怎么做。因此,我假设您的问题确实是,“我如何评估可以返回多个字符串的表达式?”

简单的解决方案似乎是将表达式作为可能的字符串列表进行评估。如果您有很多选择,那将导致非常大的数组,但是否则很简单。这个简单的类封装了基本思想:

class StrExpr(object):
  def __init__(self, str=None, *args):
    '''Make a StrExpr from a single string and/or one or more iterators'''        
    self.alts = [str] if str is not None else []
    for arg in args: self.alts.extend(arg)
  def __add__(self, other):
    '''Return a new StrExpr from this one concatenated with another one'''
    if not isinstance(other, StrExpr): raise NotImplemented
    return StrExpr(None, (l + ' ' + r for l in self.alts for r in other.alts))
  def __or__(self, other):
    '''Return a new StrExpr containing alternatives from this
       one and another one.
    '''
    if not isinstance(other, StrExpr): raise NotImplemented
    return StrExpr(None, self.alts, other.alts)
  def __str__(self):
    return str(self.alts)
  def __repr__(self):
    return "StrExpr"+str(self.alts)

快速测试:

>>> a = ( StrExpr("i") + StrExpr("want") + StrExpr("to") + StrExpr("turn")
...     + (StrExpr("on") | StrExpr("off")) + StrExpr("the") + StrExpr("lights")
...     + (StrExpr("now") | StrExpr("later") | StrExpr("tomorrow"))
...     )
>>> a
StrExpr['i want to turn on the lights now', 'i want to turn on the lights later', 'i want to turn on the lights tomorrow', 'i want to turn off the lights now', 'i want to turn off the lights later', 'i want to turn off the lights tomorrow']
>>> print('\n'.join(a.alts))
i want to turn on the lights now
i want to turn on the lights later
i want to turn on the lights tomorrow
i want to turn off the lights now
i want to turn off the lights later
i want to turn off the lights tomorrow

更Python化的解决方案是使StrExpr成为懒惰地产生其替代方案的生成器。但是原理相似。

© www.soinside.com 2019 - 2024. All rights reserved.