This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.2 KiB

  1. """
  2. Transform a Forest
  3. ==================
  4. This example demonstrates how to subclass ``TreeForestTransformer`` to
  5. directly transform a SPPF.
  6. """
  7. from lark import Lark
  8. from lark.parsers.earley_forest import TreeForestTransformer, handles_ambiguity, Discard
  9. class CustomTransformer(TreeForestTransformer):
  10. @handles_ambiguity
  11. def sentence(self, trees):
  12. return next(tree for tree in trees if tree.data == 'simple')
  13. def simple(self, children):
  14. children.append('.')
  15. return self.tree_class('simple', children)
  16. def adj(self, children):
  17. raise Discard()
  18. def __default_token__(self, token):
  19. return token.capitalize()
  20. grammar = """
  21. sentence: noun verb noun -> simple
  22. | noun verb "like" noun -> comparative
  23. noun: adj? NOUN
  24. verb: VERB
  25. adj: ADJ
  26. NOUN: "flies" | "bananas" | "fruit"
  27. VERB: "like" | "flies"
  28. ADJ: "fruit"
  29. %import common.WS
  30. %ignore WS
  31. """
  32. parser = Lark(grammar, start='sentence', ambiguity='forest')
  33. sentence = 'fruit flies like bananas'
  34. forest = parser.parse(sentence)
  35. tree = CustomTransformer(resolve_ambiguity=False).transform(forest)
  36. print(tree.pretty())
  37. # Output:
  38. #
  39. # simple
  40. # noun Flies
  41. # verb Like
  42. # noun Bananas
  43. # .
  44. #