forked from lark-parser/lark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfruitflies.py
58 lines (45 loc) · 1.09 KB
/
fruitflies.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Handling Ambiguity
==================
A demonstration of ambiguity
This example shows how to use get explicit ambiguity from Lark's Earley parser.
"""
import sys
from lark import Lark, tree
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')
sentence = 'fruit flies like bananas'
def make_png(filename):
tree.pydot__tree_to_png( parser.parse(sentence), filename)
def make_dot(filename):
tree.pydot__tree_to_dot( parser.parse(sentence), filename)
if __name__ == '__main__':
print(parser.parse(sentence).pretty())
# make_png(sys.argv[1])
# make_dot(sys.argv[1])
# Output:
#
# _ambig
# comparative
# noun fruit
# verb flies
# noun bananas
# simple
# noun
# fruit
# flies
# verb like
# noun bananas
#
# (or view a nicer version at "./fruitflies.png")