-
Notifications
You must be signed in to change notification settings - Fork 2
/
Tossup.py
95 lines (69 loc) · 3.11 KB
/
Tossup.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from utils import sanitize
import re
import json
num_regex = '^([\s]*<strong>[\d]+\.[\s]*<\/strong>[\s]*|[\s]*[\d]+\.[\s]*)'
tb_regex = '^([\s]*<strong>TB\.[\s]*<\/strong>[\s]*|[\s]*TB\.[\s]*)'
class InvalidTossup(Exception):
def __init__(self, *args):
self.args = [a for a in args]
def __str__(self):
s = '*' * 50 + '\n'
s += 'Invalid tossup {0}!\n'.format(self.args[2])
s += 'The problem is in field: {0}, which has value: {1}\n'.format(self.args[0], self.args[1])
s += '*' * 50 + '\n'
return s.decode('utf-8')
class Tossup:
def __init__(self, question='', answer='', number='', packet=None, tournament=None):
self.question = question
self.answer = answer
self.number = number
self.question = re.sub(num_regex, '', self.question)
self.question = re.sub(tb_regex, '', self.question)
if self.question.startswith('<strong>'):
self.question = '<strong>' + re.sub('^[\d]+\.[\s]*', '', self.question[8:])
self.question = '<strong>' + re.sub('^TB\.[\s]*', '', self.question[8:])
self.answer = self.answer.replace('<strong><em>', '<req>')
self.answer = self.answer.replace('<em><strong>', '<req>')
self.answer = self.answer.replace('</em></strong>', '</req>')
self.answer = self.answer.replace('</strong></em>', '</req>')
self.answer_sanitized = sanitize(self.answer, [])
self.question_sanitized = sanitize(self.question, [])
self.packet = packet
self.tournament = tournament
def to_json(self):
return json.dumps(self.to_dict(), indent=4) + '\n'
def to_dict(self):
return {'question': self.question,
'answer': self.answer,
'number': self.number,
'answer_sanitized': self.answer_sanitized,
'question_sanitized': self.question_sanitized,
'packet': self.packet,
'tournament': self.tournament}
def to_latex(self):
answer = self.answer.replace('<req>', r'\ans{')
answer = answer.replace('</req>', '}')
answer = answer.replace('<b>', r'\ans{')
answer = answer.replace('</b>', '}')
question = self.question.replace('<i>', r'{\it ')
question = question.replace('</i>', '}')
answer = answer.replace('“', '``')
answer = answer.replace('”', "''")
question = question.replace('“', '``')
question = question.replace('”', "''")
return r'\tossup{{{0}}}{{{1}}}'.format(question, answer) + '\n'
def is_valid(self):
self.valid = False
if self.question == '':
raise InvalidTossup('question', self.question, self.number)
if self.answer == '':
raise InvalidTossup('answer', self.answer, self.number)
self.valid = True
return True
def __unicode__(self):
s = '\n'
s += '{0}\nANSWER: {1}'.format(self.question, self.answer)
s += '\n'
return s.decode('utf-8')
def __str__(self):
return self.__unicode__()