더북(TheBook)

데이터셋의 전처리를 위한 함수를 정의합니다.

코드 10-26 데이터셋 전처리 함수 정의

def unicode_to_ascii(s):
    return ''.join(c for c in unicodedata.normalize('NFD', s)
                   if unicodedata.category(c) != 'Mn')

def preprocess_sentence(w):
    w = unicode_to_ascii(w.lower().strip()) ------ 소문자로 전환
    w = re.sub(r"([?.!,¿])", r" \1 ", w) ------ 특수 문자 제거
    w = re.sub(r'[" "]+', " ", w) ------ 단어와 그 뒤에 오는 구두점 사이에 공백을 삽입( “she is here.” → “she is here . ”)
    w = re.sub(r"[^a-zA-Z?.!,¿]+", " ", w) ------ a-z, A-Z, ., ?, ! 등을 제외하고 모두 공백으로 바꿈
    w = w.rstrip().strip() ------ 공백 문자 제거
    w = '<start> ' + w + ' <end>' ------ 문장의 시작 <start>와 종료 <end> 토큰 생성(모델이 예측을 시작하고 종료할 시기를 알 수 있도록 시작과 끝을 지정)
    return w

지금까지의 전처리가 정상적으로 수행되는지 확인해 보겠습니다.

코드 10-27 데이터 전처리 확인

en_sentence = u"May I borrow this book?"
sp_sentence = u"¿Puedo tomar prestado este libro?"
print(preprocess_sentence(en_sentence))
print(preprocess_sentence(sp_sentence).encode('utf-8'))
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.