gpt4 book ai didi

python - 如何匹配 pyPEG 中的无序事物?

转载 作者:行者123 更新时间:2023-12-01 03:24:42 25 4
gpt4 key购买 nike

我有以下文件:

orange
apple
orange
apple
apple
lime
banana

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

class Banana:
grammar = ....

class Apple:
...

我必须无序地匹配每个水果,我无法预先告诉顺序是什么。如何设置 FruitBasket 语法来匹配它们?

class FruitBasket:
grammar = ?????

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

最佳答案

使用 list :

A list instance which is not derived from pypeg2.Concat represents different options. They're tested in their sequence. The first option which parses is chosen, the others are not tested any more. If none matches, a SyntaxError is raised.

例如:

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

关于python - 如何匹配 pyPEG 中的无序事物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41499618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com