我有以下文件:
orange
apple
orange
apple
apple
lime
banana
每种类型的水果都有一个与之匹配的类:
class Banana:
grammar = ....
class Apple:
...
我必须匹配每个水果无序,我不能预先告诉将是什么订单。如何设置FruitBasket
语法以匹配' em?
class FruitBasket:
grammar = ?????
ps:水果实际上是复杂的规则,每种水果类型代表不同的代码块,例如函数,原型,全局变量等。
答案 0 :(得分:2)
使用list:
不是从
list
派生的pypeg2.Concat
实例代表不同的选项。他们按顺序进行了测试。选择解析的第一个选项,其他选项不再测试。如果没有匹配,则会引发SyntaxError
。
例如:
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>])