1

我有以下文件:

orange
apple
orange
apple
apple 
lime
banana

每种水果都有一个与之匹配的类:

class Banana:
    grammar = ....

class Apple:
    ...

我必须匹配每个未排序的水果,我无法预先确定订单是什么。如何设置FruitBasket语法来匹配它们?

class FruitBasket:
    grammar = ?????

ps:水果其实是复杂的规则,每个水果类型代表不同的代码块,比如函数、原型、全局变量等。

4

1 回答 1

2

使用列表

list不是派生自的实例pypeg2.Concat代表不同的选项。它们按顺序进行测试。选择第一个解析的选项,其他的不再测试。如果没有匹配,SyntaxError则引发 a。

例如:

from pypeg2 import K, List, maybe_some, parse

class Apple:
    grammar = K('apple')

class Banana:
    grammar = K('banana')

class Lime:
    grammar = K('lime')

class Orange:
    grammar = K('orange')

class FruitBasket(List):
    '''An unordered collection of zero or more fruits'''
    grammar = maybe_some([Apple, Banana, Lime, Orange])


if __name__ == '__main__':

    fruit = '''
        orange
        apple
        orange
        apple
        apple 
        lime
        banana
    '''

    print(parse(fruit, FruitBasket))

输出:

FruitBasket([<__main__.Orange object at 0x7ffa4991d8d0>, <__main__.Apple object at 0x7ffa49922c18>, <__main__.Orange object at 0x7ffa49927a58>, <__main__.Apple object at 0x7ffa499279b0>, <__main__.Apple object at 0x7ffa49927908>, <__main__.Lime object at 0x7ffa421ad828>, <__main__.Banana object at 0x7ffa421ad8d0>])
于 2017-02-27T22:31:24.790 回答