-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_test_parser.py
More file actions
78 lines (68 loc) · 2.1 KB
/
_test_parser.py
File metadata and controls
78 lines (68 loc) · 2.1 KB
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
71
72
73
74
75
76
77
78
import re, sys, json
raw = sys.stdin.read()
def strip_num_prefix(s):
return re.sub(r'^\d+\.\s*', '', s).strip()
def is_question_line(line):
return bool(re.match(r'^\d+\.', line.strip()))
def parse_answer_line(line):
s = line.strip()
if not s:
return None
correct = False
# '- +text' (space optional between - and +)
if re.match(r'^-\s*\+', s):
correct = True
text = re.sub(r'^-\s*\+\s*', '', s).strip()
# '+- text'
elif re.match(r'^\+\s*-\s*', s):
correct = True
text = re.sub(r'^\+\s*-\s*', '', s).strip()
# 'text+' trailing plus
elif re.match(r'^-\s+', s) and s.rstrip().endswith('+'):
correct = True
text = re.sub(r'^-\s+', '', s.rstrip()[:-1]).strip()
# normal wrong answer
elif re.match(r'^-\s*', s):
correct = False
text = re.sub(r'^-\s*', '', s).strip()
else:
return None
return (text.strip(), correct)
lines = raw.splitlines()
questions = []
cur_q = None
cur_opts = []
def flush():
global cur_q, cur_opts
if cur_q and cur_opts:
texts = [t for t, _ in cur_opts]
rights = [i for i, (_, c) in enumerate(cur_opts) if c]
correct = rights[0] if len(rights) == 1 else rights
questions.append({'question': cur_q, 'answers': texts, 'correct': correct})
cur_q = None
cur_opts = []
for line in lines:
line = line.rstrip()
if not line:
continue
if is_question_line(line):
flush()
cur_q = strip_num_prefix(line).rstrip(':').strip()
cur_opts = []
continue
parsed = parse_answer_line(line)
if parsed and cur_q is not None:
text, correct = parsed
if text:
cur_opts.append((text, correct))
flush()
for i, q in enumerate(questions, 1):
rights = q['correct'] if isinstance(q['correct'], list) else [q['correct']]
qtext = q['question'][:90]
print(f'Q{i}: {qtext}')
for j, a in enumerate(q['answers']):
mark = 'V' if j in rights else ' '
atext = a[:80]
print(f' [{mark}] {atext}')
print()
print(f'Total parsed: {len(questions)}')