귀퉁이 서재

NLP - 2. 텍스트 토큰화(Text Tokenization) 본문

자연어 처리 (NLP)

NLP - 2. 텍스트 토큰화(Text Tokenization)

Baek Kyun Shin 2020. 2. 10. 20:23

NLP에서 텍스트 자체를 바로 피처로 사용할 수는 없습니다. 사전에 텍스트 전처리 작업이 반드시 필요합니다. 텍스트 전처리를 위해서는 클렌징, 토큰화, 불용어 제거, 정규화 등의 작업이 필요합니다. 

텍스트 전처리 첫번째 시간으로 이번 장에서는 텍스트 토큰화에 대해 알아보겠습니다. (참고로, 파이썬 머신러닝 완벽 가이드(권철민 저)와 딥 러닝을 이용한 자연어 처리 입문(유원준 저)를 요약정리한 것입니다.)

그전에 말뭉치(Corpus, 코퍼스)의 뜻에 대해 먼저 알아보겠습니다. 말뭉치를 위키피디아에서 검색하면 아래와 같이 나옵니다.

말뭉치 또는 코퍼스(Corpus)는 자연언어 연구를 위해 특정한 목적을 가지고 언어의 표본을 추출한 집합이다.

(Reference1) 어렵게 설명이 되어 있는데 그냥 우리가 사용하는 텍스트 표본이라고 보시면 되겠습니다.

토큰(Token)이란 문법적으로 더 이상 나눌 수 없는 언어요소를 뜻합니다. 텍스트 토큰화(Text Tokenization)란 말뭉치로부터 토큰을 분리하는 작업을 뜻합니다.

예를 들어, "There is an apple"이라는 말뭉치(Corpus)가 있을 때 이를 토큰화한다고 하면, "There", "is", "an", "apple"로 나뉩니다. 쉽죠? 하지만 이는 아주 단순한 예에 불과하고 깊이 있게 들어가면 복잡한 것들이 많습니다.

텍스트 토큰화의 유형은 문장 토큰화와 단어 토큰화로 나눌 수 있습니다. 문장 토큰화는 텍스트에서 문장을 분리하는 작업을 뜻하고, 단어 토큰화는 문자아에서 단어를 토큰으로 분리하는 작업을 뜻합니다.

문장 토큰화(Sentence Tokenization)

문장 토큰화는 문장의 마침표(.), 개행문자(\n), 느낌표(!), 물음표(?) 등 문장의 마지막을 뜻하는 기호에 따라 분리하는 것이 일반적입니다. 하지만 꼭 그렇지는 않습니다. 예를 들어, "Hello! I'm a Ph.D student."라는 텍스트를 문장 토큰화할 경우 "Hello", "I'm a ph.D student"로 2개의 문장으로 분리를 해야하는데, 마침표(.)를 기준으로 문장 토큰화를 하면 "Hello", "I'm a ph", "D student"로 3개의 문장으로 엉터리로 분리하게 됩니다. 따라서 100% 정확하게 문장을 분리하는 것은 쉬운 일이 아닙니다. 

 NLTK를 통해 문장 토큰화를 실습해보겠습니다.

from nltk import sent_tokenize
text_sample = 'The Matrix is everywhere its all around us, here even in this room. You can see it out your window or on your television. You feel it when you go to work, or go to church or pay your taxes.'
tokenized_sentences = sent_tokenize(text_sample)
print(tokenized_sentences)
['The Matrix is everywhere its all around us, here even in this room.', 'You can see it out your window or on your television.', 'You feel it when you go to work, or go to church or pay your taxes.']

3개의 문장으로 잘 분리가 되었습니다. 이제, Ph.D를 포함하는 문장으로도 실습해보겠습니다.

text_sample = 'I am actively looking for Ph.D. students. and you are a Ph.D student.'
tokenized_sentences = sent_tokenize(text_sample)
print(tokenized_sentences)
['I am actively looking for Ph.D. students.', 'and you are a Ph.D student.']

마침표(.)를 기준으로 분리하지 않았기 때문에 정확히 분리한 것을 볼 수 있습니다.

단어 토큰화 (Word Tokenization)

단어 토큰화는 기본적으로 띄어쓰기를 기준으로 합니다. 영어는 보통 띄어쓰기로 토큰이 구분되는 반면, 한국어는 띄어쓰기 만으로 토큰을 구분하기는 어렵습니다. 심지어 띄어쓰기가 잘못 되어 있는 경우도 허다하고요. 우선은 영어를 기반으로 실습해보겠습니다.

from nltk import word_tokenize

sentence = "The Matrix is everywhere its all around us, here even in this room."
words = word_tokenize(sentence)
print(words)
['The', 'Matrix', 'is', 'everywhere', 'its', 'all', 'around', 'us', ',', 'here', 'even', 'in', 'this', 'room', '.']

띄어쓰기를 기반으로 분리를 하되 콤마(,)와 마침표(.)는 별도의 토큰으로 구분했습니다. 어퍼스트로피(')가 있는 경우에는 어떻게 구분할까요?

sentence = "Don't be fooled by the dark sounding name, Mr. Jone's Orphanage is as cheery as cheery goes for a pastry shop."
words = word_tokenize(sentence)
print(words)
['Do', "n't", 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', ',', 'Mr.', 'Jone', "'s", 'Orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop', '.']

Don't 는Do와 n't로 구분했고, Jone's는 Jone'과 's로 구분했습니다. 구두점으로 분류를 하는 WordPunctTokenizer로도 확인해보겠습니다.

from nltk.tokenize import WordPunctTokenizer  
sentence = "Don't be fooled by the dark sounding name, Mr. Jone's Orphanage is as cheery as cheery goes for a pastry shop."
words = WordPunctTokenizer().tokenize(sentence)
print(words)
['Don', "'", 't', 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', ',', 'Mr', '.', 'Jone', "'", 's', 'Orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop', '.']

Don't는 Don, ', t로 Jone's는 Jone, ', s로 구분한 것을 볼 수 있습니다. 어퍼스트로피를 별도의 토큰으로 본 것입니다.

마지막으로 nltk가 아닌 keras의 text_to_word_sequence로 실습해보겠습니다.

from tensorflow.keras.preprocessing.text import text_to_word_sequence
sentence = "Don't be fooled by the dark sounding name, Mr. Jone's Orphanage is as cheery as cheery goes for a pastry shop."
words = text_to_word_sequence(sentence)
print(words)
["don't", 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', 'mr', "jone's", 'orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop']

keras의 text_to_word_sequence는 모든 알파벳을 소문자로 바꾸고, 구두점(컴마, 마침표 등)을 없애고, 어퍼스트로피(')도 보존하여 토큰을 제대로 구분해줍니다.

문장 토큰화와 단어 토큰화 모두 정규 표현식을 활용하여 토큰화하는 작업도 가능합니다. 문장 토큰화는 문장 자체가 중요한 의미를 가질 경우 사용되며, 일반적으로는 단어 토큰화만 사용해도 충분합니다.

References

Reference1: 위키피디아 (말뭉치)

Reference2: 딥 러닝을 이용한 자연어 처리 입문 (토큰화)

Reference3: 파이썬 머신러닝 완벽 가이드 (권철민 저)

 

Comments