Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: lark_parser_demo.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- This script demonstrates parsing behavior using Lark grammar with and without a question mark.
- Requirements:
- - Python 3.x
- - Lark library
- Functions:
- - line(): A utility function to print divider lines for better readability.
- - parse_and_print(grammar, grammar_type): Parses the input string using the provided grammar and prints the parsed results.
- Usage:
- 1. Run the script using Python 3.x interpreter.
- 2. The script will parse an input string using two different grammars and print the parsed results.
- Additional Notes:
- - The script defines two grammars: one without a question mark and another with rules starting with a question mark.
- - It parses an input string using both grammars and displays the parsed results.
- - It's recommended to have Python 3.x and the Lark library installed to run the script.
- """
- import lark
- # Define grammars with different rules
- grammar_first = """
- start: rule1 rule2
- rule1: /\w+/ /\w+/
- | "(" /\w+/ ")"
- rule2: /\w+/ /\w+/
- | "(" /\w+/ ")"
- %ignore " "
- """
- grammar_second = """
- start: rule1 rule2
- ?rule1: /\w+/ /\w+/
- | "(" /\w+/ ")"
- ?rule2: /\w+/ /\w+/
- | "(" /\w+/ ")"
- %ignore " "
- """
- def line():
- print("-" * 40)
- def parse_and_print(grammar, grammar_type):
- print(f"Parsing with {grammar_type} grammar:\n")
- print("Grammar:")
- print(grammar)
- line()
- parser = lark.Lark(grammar)
- parsed = parser.parse("example sample (another_example)")
- print()
- for idx, ch in enumerate(parsed.children, start=1):
- if isinstance(ch, lark.Tree):
- print(f"Tree {idx} with name {ch.data}:")
- for sub_ch in ch.children:
- print(f" {sub_ch.value}")
- print()
- elif isinstance(ch, lark.Token):
- print(f"Token {idx} with value {ch.value}")
- line()
- # Test with different grammars
- parse_and_print(grammar_first, "First Grammar")
- parse_and_print(grammar_second, "Second Grammar")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement