othamoth's picture
Upload 30 files
8016893 verified
Raw History Blame
1.7 kB
import json
class CharTokenizer:
def __init__(self, max_len=100):
self.char2idx = {}
self.idx2char = {}
self.max_len = max_len
self.pad_token = "<PAD>"
self.unk_token = "<UNK>"
self.add_token(self.pad_token)
self.add_token(self.unk_token)
def add_token(self, token):
if token not in self.char2idx:
idx = len(self.char2idx)
self.char2idx[token] = idx
self.idx2char[idx] = token
def build_vocab(self, texts):
unique_chars = set()
for text in texts:
unique_chars.update(list(text))
for char in sorted(list(unique_chars)):
self.add_token(char)
def encode(self, text):
indices = [self.char2idx.get(char, self.char2idx[self.unk_token]) for char in text]
if len(indices) > self.max_len:
indices = indices[:self.max_len]
padding = [self.char2idx[self.pad_token]] * (self.max_len - len(indices))
return indices + padding
def save(self, path):
with open(path, 'w', encoding='utf-8') as f:
json.dump({
'char2idx': self.char2idx,
'max_len': self.max_len
}, f, ensure_ascii=False, indent=2)
@classmethod
def load(cls, path):
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
tokenizer = cls(max_len=data['max_len'])
tokenizer.char2idx = data['char2idx']
tokenizer.idx2char = {int(v): k for k, v in data['char2idx'].items()}
return tokenizer
def __len__(self):
return len(self.char2idx)