-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbabi.py
66 lines (48 loc) · 1.44 KB
/
babi.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
class Query(object):
def __init__(self, sentence, answer, fact):
self.sentence = sentence
self.answer = answer
self.fact = fact
class Sentence(object):
def __init__(self, sentence):
self.sentence = sentence
def split(sentence):
return sentence.lower().replace('.', '').replace('?', '').split()
def convert(vocab, words):
return [vocab[w] for w in words]
def parse_line(vocab, line):
if '\t' in line:
# question line
question, answer, fact_id = line.split('\t')
aid = convert(vocab, [answer])[0]
words = split(question)
wid = convert(vocab, words)
ids = list(map(int, fact_id.split(' ')))
return Query(wid, aid, ids)
else:
# sentence line
words = split(line)
wid = convert(vocab, words)
return Sentence(wid)
def parse_data(vocab, lines):
data = []
all_data = []
last_id = 0
for line in lines:
line = line.strip()
pos = line.find(' ')
sid = int(line[:pos])
if sid == 1:
if len(data) > 0:
all_data.append(data)
data = []
last_id = 0
assert sid == last_id + 1
data.append(parse_line(vocab, line[pos + 1:]))
last_id = sid
if len(data) > 0:
all_data.append(data)
return all_data
def read_data(vocab, path):
with open(path) as f:
return parse_data(vocab, f)