Advertisement
Python253

lark_parser_demo

May 3rd, 2024
871
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: lark_parser_demo.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script demonstrates parsing behavior using Lark grammar with and without a question mark.
  9.  
  10. Requirements:
  11. - Python 3.x
  12. - Lark library
  13.  
  14. Functions:
  15. - line(): A utility function to print divider lines for better readability.
  16. - parse_and_print(grammar, grammar_type): Parses the input string using the provided grammar and prints the parsed results.
  17.  
  18. Usage:
  19. 1. Run the script using Python 3.x interpreter.
  20. 2. The script will parse an input string using two different grammars and print the parsed results.
  21.  
  22. Additional Notes:
  23. - The script defines two grammars: one without a question mark and another with rules starting with a question mark.
  24. - It parses an input string using both grammars and displays the parsed results.
  25. - It's recommended to have Python 3.x and the Lark library installed to run the script.
  26. """
  27.  
  28. import lark
  29.  
  30. # Define grammars with different rules
  31. grammar_first = """
  32. start:   rule1   rule2
  33.  
  34. rule1:      /\w+/  /\w+/
  35.   |  "("  /\w+/  ")"
  36.  
  37. rule2:      /\w+/  /\w+/
  38.   |  "("  /\w+/  ")"
  39.  
  40. %ignore " "
  41. """
  42.  
  43. grammar_second = """
  44. start:   rule1   rule2
  45.  
  46. ?rule1:      /\w+/  /\w+/
  47.   |  "("  /\w+/  ")"
  48.  
  49. ?rule2:      /\w+/  /\w+/
  50.   |  "("  /\w+/  ")"
  51.  
  52. %ignore " "
  53. """
  54.  
  55.  
  56. def line():
  57.     print("-" * 40)
  58.  
  59.  
  60. def parse_and_print(grammar, grammar_type):
  61.     print(f"Parsing with {grammar_type} grammar:\n")
  62.     print("Grammar:")
  63.     print(grammar)
  64.     line()
  65.  
  66.     parser = lark.Lark(grammar)
  67.     parsed = parser.parse("example sample (another_example)")
  68.     print()
  69.  
  70.     for idx, ch in enumerate(parsed.children, start=1):
  71.         if isinstance(ch, lark.Tree):
  72.             print(f"Tree {idx} with name {ch.data}:")
  73.             for sub_ch in ch.children:
  74.                 print(f"   {sub_ch.value}")
  75.             print()
  76.         elif isinstance(ch, lark.Token):
  77.             print(f"Token {idx} with value {ch.value}")
  78.  
  79.     line()
  80.  
  81.  
  82. # Test with different grammars
  83. parse_and_print(grammar_first, "First Grammar")
  84. parse_and_print(grammar_second, "Second Grammar")
  85.  
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement