使用pytorch_pretrained_bert.BertTokenizer对中文文本进行编码长度限制
发布时间:2024-01-02 07:15:56
import torch
from pytorch_pretrained_bert import BertTokenizer
text = "今天天气不错,适合出去玩。但是我还有很多工作要做,不能出去玩。"
# 加载中文预训练模型的tokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
# 对文本进行编码
tokens = tokenizer.tokenize(text)
# 添加特殊符号[CLS]和[SEP]
tokens = ['[CLS]'] + tokens + ['[SEP]']
# 将标记转换为对应的索引编号
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# 判断document长度是否超过限制
max_seq_length = 1000
if len(input_ids) > max_seq_length:
input_ids = input_ids[:max_seq_length]
# 将索引编号的列表转换为PyTorch张量
input_ids = torch.tensor(input_ids)
print(input_ids)
