mirror of https://github.com/lark-parser/lark.git
1
Examples
Erez Shinan edited this page 2017-10-31 19:07:44 +02:00
Table of Contents
Here are some tiny examples of using Lark.
For more examples, check out the examples folder.
Tiny Calculator
from lark import Lark, InlineTransformer
parser = Lark('''?sum: product
| sum "+" product -> add
| sum "-" product -> sub
?product: item
| product "*" item -> mul
| product "/" item -> div
?item: NUMBER -> number
| "-" item -> neg
| "(" sum ")"
%import common.NUMBER
%import common.WS
%ignore WS
''', start='sum')
class CalculateTree(InlineTransformer):
from operator import add, sub, mul, truediv as div, neg
number = float
def calc(expr):
return CalculateTree().transform( parser.parse(expr) )
In the grammar, we shape the resulting tree. The '->' operator renames branches, and the '?' prefix tells Lark to inline single values. (see the tutorial for a more in-depth explanation)
Then, the transformer calculates the tree and returns a number:
>>> calc("(200 + 3*-3) * 7")
1337.0
Fruit Flies Like Bananas
Lark can automatically resolve ambiguity by choosing the simplest solution. Or, you can ask it to return all the possible parse trees, wrapped in a meta "_ambig" node.
Here's a toy example to parse the famously ambiguous phrase: "fruit flies like bananas"
from lark import Lark
grammar = """
sentence: noun verb noun -> simple
| noun verb "like" noun -> comparative
noun: adj? NOUN
verb: VERB
adj: ADJ
NOUN: "flies" | "bananas" | "fruit"
VERB: "like" | "flies"
ADJ: "fruit"
%import common.WS
%ignore WS
"""
parser = Lark(grammar, start='sentence', ambiguity='explicit') # Explicit ambiguity in parse tree!
tree = parser.parse('fruit flies like bananas')
from lark.tree import pydot__tree_to_png # Just a neat utility function
pydot__tree_to_png(tree, "examples/fruitflies.png")