获取 BertTokenizer 生成的子词索引(在 transformers 库中)

Get the index of subwords produced by BertTokenizer (in transformers library)

BertTokenizer 可以将一个句子标记为标记列表,其中一些长词例如“嵌入”被拆分为几个子词,即 'em'、“##bed”、“##ding”和“##s”。

有没有办法定位子词?例如,

t = BertTokenizer.from_pretrained('bert-base-uncased')

tokens = t('word embeddings', add_special_tokens=False)
location = locate_subwords(tokens)

我希望 location[0, 1, 1, 1, 1] 对应 ['word', 'em', '##bed', '##ding', '##s'],其中 0 表示普通词,1 表示子词。

快速标记器 return Batchencoding object that has a built-in word_ids:

from transformers import BertTokenizerFast

t = BertTokenizerFast.from_pretrained('bert-base-uncased')

tokens = t('word embeddings are vectors', add_special_tokens=False, return_attention_mask=False, return_token_type_ids=False)
print(tokens.word_ids())

输出:

[0, 1, 1, 1, 1, 2, 3]