-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.py
59 lines (52 loc) · 1.49 KB
/
parse.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
import sys
from copy import deepcopy
from pprint import pprint
from collections import defaultdict
def parse_sequence(header):
_, *header = header.split(' ')
problem = tuple()
for item in header:
try:
problem += (int(item),)
except ValueError:
pass
return problem
def parse_header(header):
current = header.split('[')[1].split(']')[0]
if (current.startswith('extend') or
current.startswith('variation')):
current = parse_sequence(current)
return current
def parse_datum(line):
a, b = line.split(':')
b = b.strip()
if b in ['?', '']:
b = None
else:
try:
if a not in ['next_terms_entered', 'position']:
b = float(b)
else:
b = int(b)
except ValueError:
pass
return a, b
def save(data, current, section):
if current is not None and current != 'BOOK_KEEPING':
data[current] = deepcopy(section)
section.clear()
def parse(filename):
data = dict()
current = None
section = defaultdict(list)
with open(filename, 'r') as infile:
for line in infile:
if line.startswith('['):
save(data, current, section)
current = parse_header(line)
elif line not in ['', '\n']:
k, v = parse_datum(line)
if k != 'start_time':
section[k].append(v)
save(data, current, section)
return data