-
Notifications
You must be signed in to change notification settings - Fork 13
/
vocab.py
50 lines (40 loc) · 1.43 KB
/
vocab.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
import pickle
class Vocab(object):
def __init__(self, counter, specials=["<pad>", "<unk>"]):
self.pad_index = 0
self.unk_index = 1
counter = counter.copy()
self.itos = list(specials)
for tok in specials:
del counter[tok]
# sort by frequency, then alphabetically
words_and_frequencies = sorted(counter.items(), key=lambda tup: tup[0])
words_and_frequencies.sort(key=lambda tup: tup[1], reverse=True)
for word, _ in words_and_frequencies:
self.itos.append(word)
# stoi is simply a reverse dict for itos
self.stoi = {tok: i for i, tok in enumerate(self.itos)}
def __eq__(self, other):
if self.stoi != other.stoi:
return False
if self.itos != other.itos:
return False
return True
def __len__(self):
return len(self.itos)
def extend(self, v):
words = v.itos
for w in words:
if w not in self.stoi:
self.itos.append(w)
self.stoi[w] = len(self.itos) - 1
return self
@staticmethod
def load_vocab(vocab_path: str):
with open(vocab_path, "rb") as f:
print('Loading vocab from:', vocab_path)
return pickle.load(f)
def save_vocab(self, vocab_path):
with open(vocab_path, "wb") as f:
print('Saving vocab to:', vocab_path)
pickle.dump(self, f)