This repository has been archived by the owner on Nov 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Grammars.py
70 lines (59 loc) · 1.52 KB
/
Grammars.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
59
60
61
62
63
64
65
66
67
68
69
70
import random as rd
# Example Grammar rules
rules = {
"S":[
["The", "N", "V"]
],
"N":[
["Adj","cat"],
["Adj","dog"],
["Adj","tiger"]
],
"V":[
["meows", "A"],
["barks", "A"],
["moos", "A"]
],
"Adj": [
["Stinky"],
["Giant"],
["Blue"]
],
"A": [
["and", "the", "N", "Va"]
],
"Va": [
["sings"],
["yawns"],
["eats grass"]
]
}
# Contributed by Tiger Sachase
# Used to parse any list of strings and insert them in place in a list
def generate_items(items):
for item in items:
if isinstance(item, list):
for subitem in generate_items(item):
yield subitem
else:
yield item
# Our expansion algo
def expansion(start):
for element in start:
if element in rules:
loc = start.index(element)
start[loc] = rd.choice(rules[element])
result = [item for item in generate_items(start)]
for item in result:
if not isinstance(item, list):
if item in rules:
result = expansion(result)
return result
def to_string(result):
return ' '.join(result)
# An example test you can run to see it at work
result = ["S"]
print(result) # Print our starting result
result = expansion(result) # Expand our starting list
final = to_string(result)
print(final) # Print the final result