코드 2-3 간단한 텍스트 토크나이저 구현
class SimpleTokenizerV1:
def __init__(self, vocab):
self.str_to_int = vocab ----- encode 메서드와 decode 메서드에서 참조할 수 있도록 어휘사전을 클래스의 속성으로 저장합니다.
self.int_to_str = {i:s for s,i in vocab.items()} ----- 토큰 ID를 원본 텍스트 토큰으로 매핑하는 역어휘사전을 만듭니다.
def encode(self, text): ----- 입력 텍스트를 처리하여 토큰 ID로 바꿉니다.
preprocessed = re.split(r'([,.?_!"()\']|--|\s)', text)
preprocessed = [
item.strip() for item in preprocessed if item.strip()
]
ids = [self.str_to_int[s] for s in preprocessed]
return ids
def decode(self, ids): ----- 토큰 ID를 텍스트로 되돌립니다.
text = " ".join([self.int_to_str[i] for i in ids])
text = re.sub(r'\s+([,.?!"()\'])', r'\1', text) ----- 지정된 구두점 문자 앞의 공백을 삭제합니다.
return text