Skip to content

Commit aefad12

Browse files
Merge pull request #79 from BogdanDidenko/backward_convert
Add method for converting ids to tokens.
2 parents 870e56f + 2d7a34b commit aefad12

1 file changed

Lines changed: 18 additions & 6 deletions

File tree

‎tokenization.py‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,20 @@ def load_vocab(vocab_file):
8282
return vocab
8383

8484

85+
def convert_by_vocab(vocab, items):
86+
"""Converts a sequence of [tokens|ids] using the vocab."""
87+
output = []
88+
for item in items:
89+
output.append(vocab[item])
90+
return output
91+
92+
8593
def convert_tokens_to_ids(vocab, tokens):
86-
"""Converts a sequence of tokens into ids using the vocab."""
87-
ids = []
88-
for token in tokens:
89-
ids.append(vocab[token])
90-
return ids
94+
return convert_by_vocab(vocab, tokens)
95+
96+
97+
def convert_ids_to_tokens(inv_vocab, ids):
98+
return convert_by_vocab(inv_vocab, ids)
9199

92100

93101
def whitespace_tokenize(text):
@@ -104,6 +112,7 @@ class FullTokenizer(object):
104112

105113
def __init__(self, vocab_file, do_lower_case=True):
106114
self.vocab = load_vocab(vocab_file)
115+
self.inv_vocab = {v: k for k, v in self.vocab.items()}
107116
self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
108117
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
109118

@@ -116,7 +125,10 @@ def tokenize(self, text):
116125
return split_tokens
117126

118127
def convert_tokens_to_ids(self, tokens):
119-
return convert_tokens_to_ids(self.vocab, tokens)
128+
return convert_by_vocab(self.vocab, tokens)
129+
130+
def convert_ids_to_tokens(self, ids):
131+
return convert_by_vocab(self.inv_vocab, ids)
120132

121133

122134
class BasicTokenizer(object):

0 commit comments

Comments
 (0)