-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar.py
43 lines (34 loc) · 958 Bytes
/
grammar.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
import random
import re
GRAMMAR = {
"START": "I will have one <order>",
"<order>": ["<coffee> and <pastry>", "<coffee> and <pastry>", "<coffee> <stars>", "<coffee> <another>"],
"<another>": ["and a <coffee> <another>", "and a <coffee>"],
"<stars>": "and I want to use my stars for a cake pop.",
"<coffee>": ["hot coffee", "iced coffee", "vanilla latte", "chai latte"],
"<pastry>": ["muffin", "brownie", "lemon loaf"]
}
TOKEN = re.compile(r"<[\w]+>")
def gramreplace(m):
gx = GRAMMAR[m.group(0)]
if isinstance(gx, list):
return random.choice(gx)
else:
return gx
# print(GRAMMAR["START"])
def match(gr, txt = None):
if not txt:
txt = gr["START"]
if not TOKEN.search(txt):
return txt
else:
mx = TOKEN.sub(gramreplace, txt)
return match(GRAMMAR, mx)
x = match(GRAMMAR)
for _ in range(1, 1000):
m = match(GRAMMAR)
print(len(m))
if len(m) > len(x):
x = m
#print(match(GRAMMAR))
print(x, len(x))