-
Notifications
You must be signed in to change notification settings - Fork 2
/
my_build_vocab.py
63 lines (49 loc) · 1.71 KB
/
my_build_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
51
52
53
54
55
56
57
58
59
60
61
62
63
import string
import json
import pickle
from collections import Counter
import nltk
from constants import FOLDER
class Vocabulary(object):
"""Simple vocabulary wrapper."""
def __init__(self):
self.word2idx = {}
self.idx2word = {}
self.idx = 0
def add_word(self, word):
if word not in self.word2idx:
self.word2idx[word] = self.idx
self.idx2word[self.idx] = word
self.idx += 1
def __call__(self, word):
if word not in self.word2idx or 'xxxx' in word:
return self.word2idx['<unk>']
return self.word2idx[word]
def __len__(self):
return len(self.word2idx)
if __name__ == '__main__':
with open( FOLDER + 'reports.json') as f:
reports = json.load(f)
counter = Counter()
for caseid, report in reports.items():
text = ''
if report['findings'] is not None:
text += report['findings']
text += ' '
if report['impression'] is not None:
text += report['impression']
text = text.lower().translate(str.maketrans('', '', string.punctuation.replace('.', '')))
text = text.replace('.', ' .')
tokens = text.strip().split()
counter.update(tokens)
words = [word for word, cnt in counter.items() if cnt >= 3]
vocab = Vocabulary()
vocab.add_word('<pad>')
vocab.add_word('<start>')
vocab.add_word('<end>')
vocab.add_word('<unk>')
for word in words:
vocab.add_word(word)
with open( FOLDER + 'vocab.pkl', 'wb') as f:
pickle.dump(vocab, f)
print('Total vocabulary size {}. Saved to {}'.format(len(vocab), 'vocab.pkl'))