Code:
$ cat foo.py
#!/usr/bin/python
def do_string(s):
for i in range(len(s)):
print i, s[i],
print
def parse_line(lines, index):
# remove line endings and whitespaces at start or end of line
current=lines[index].strip()
# split remainder
line_array=current.split(" ")
op=line_array[0]
# STRING: re-assemble string from remainder array
if op=="STRING":
do_string(" ".join(line_array[1:]))
# REPEAT: WHOO recursion!
elif op=="REPEAT":
times = int(line_array[1])
for _ in range(times):
parse_line(lines, index-1)
file = open("test.txt", "r")
lines=file.readlines()
file.close()
for i in range(len(lines)):
parse_line(lines, i)
Code:
$ cat test.txt
STRING foo
STRING bar
REPEAT 2
STRING baz
REPEAT 2
REPEAT 3
Code:
$ python foo.py
0 f 1 o 2 o
0 b 1 a 2 r
0 b 1 a 2 r
0 b 1 a 2 r
0 b 1 a 2 z
0 b 1 a 2 z
0 b 1 a 2 z
0 b 1 a 2 z
0 b 1 a 2 z
0 b 1 a 2 z
0 b 1 a 2 z
0 b 1 a 2 z
0 b 1 a 2 z