-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoc.py
55 lines (46 loc) · 1.49 KB
/
voc.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
"""
voc.py
Mar 4 2023
Gabriel Moreira
"""
import torch
from collections import Counter, OrderedDict
class Vocabulary:
def __init__(self, words):
"""
Creates vocabulary from list of words
"""
words_counter = Counter(words)
words_sorted = sorted(words_counter.items(), key=lambda x : x[1], reverse=True)
words_dict = OrderedDict(words_sorted)
self._word2idx = {key : i for i, key in enumerate(words_dict.keys())}
self._idx2word = {i : key for i, key in enumerate(words_dict.keys())}
self.length = len(self._word2idx)
def __len__(self):
return self.length
def w2i(self, src):
"""
Word (or iterable of words) to index (or list of indices)
"""
if isinstance(src, str):
return self._word2idx[src]
else:
out = []
for word in src:
out.append(self._word2idx[word])
return out
def i2w(self, src):
"""
Index (or iterable of indicex) to word (or list of words)
"""
if isinstance(src, int):
return self._idx2word[src]
else:
out = []
if isinstance(src, torch.Tensor):
for idx in src.ravel():
out.append(self._idx2word[idx.item()])
else:
for idx in src:
out.append(self._idx2word[idx])
return out