-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgenerate.py
61 lines (56 loc) · 2.01 KB
/
generate.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
import random
import re
Here is something I want to talk about::
def generate(template):
"""A really useful function.
Returns None
"""
if type(template) == dict:
obj = {}
for i in template.keys():
regex = r"^.+\|optional$"
matches = re.match(regex, i)
if matches is not None: # Optional
si = i.split('|')
if random.randint(0, 10) % 2 == 0: # ToDo: Fixed probability (50%)
obj[si[0]] = generate(template[i])
else:
obj[i] = generate(template[i])
return obj
if type(template) == list:
lst = []
it = iter(template)
while True:
r = next(it, None)
if r is None:
break
if type(r) == str:
regex = r"^\{\{repeat\(\s*\d+\s*,{0,1}\s*\d*\s*\)\}\}$"
matches = re.match(regex, r)
if matches is not None: # Repeat
s = template[0].find('(') + 1
e = template[0].find(')')
rng = template[0][s:e].replace(' ', '').split(',')
if len(rng) > 1:
repeat = random.randint(int(rng[0]), int(rng[1]))
else:
repeat = int(rng[0])
r = next(it, None) # Repeat it
if r is None:
break
for i in range(0, repeat):
lst.append(generate(r))
else:
lst.append(generate(r))
else:
lst.append(generate(r))
return lst
if type(template) == str:
regex = r"^\{{2}.+\(.*\)\}{2}$"
matches = re.match(regex, template)
if matches is not None:
k = template.find('(')
mod = __import__('methods.' + template[2:k])
return eval('mod.{}.{}'.format(template[2:k], template[2:-2]))
else:
return template