반응형

Word Tokenization 단어 토큰화

 

자연어 처리에서 크롤링 등으로 얻어낸 코퍼스 데이터가 필요에 맞게 전처리되지 않은 상태라면, 해당 데이터를 사용하고자하는 용도에 맞게 토큰화(tokenization) & 정제(cleaning) & 정규화(normalization)하는 일을 하게 됩니다. 이번 챕터에서는 그 중에서도 토큰화에 대해서 배우도록 합니다.

주어진 코퍼스(corpus)에서 토큰(token)이라 불리는 단위로 나누는 작업을 토큰화(tokenization)라고 부릅니다. 토큰의 단위가 상황에 따라 다르지만, 보통 의미있는 단위로 토큰을 정의합니다.

이 챕터에서는 토큰화에 대한 발생할 수 있는 여러가지 상황에 대해서 언급하여 토큰화에 대한 개념을 이해합니다. 뒤에서 파이썬과 NLTK 패키지, KoNLPY를 통해 실습을 진행하며 직접 토큰화를 수행해보겠습니다.

 

 


## word_tokenize는 Don't를 Do와 n't로 분리하였으며, 
## 반면 Jone's는 Jone과 's로 분리한 것을 확인할 수 있습니다.
>from nltk.tokenize import word_tokenize  
>print(word_tokenize("Don't be fooled by the dark sounding name, Mr. Jone's Orphanage is as cheery as cheery goes for a pastry shop."))  
['Do', "n't", 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', ',', 'Mr.', 'Jone', "'s", 'Orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop', '.']  


## WordPunctTokenizer는 구두점을 별도로 분류하는 특징을 갖고 있기때문에, 앞서 확인했던
## word_tokenize와는 달리 Don't를 Don과 '와 t로 분리하였으며, 
## 이와 마찬가지로 Jone's를 Jone과 '와 s로 분리한 것을 확인할 수 있습니다.
>from nltk.tokenize import WordPunctTokenizer  
>print(WordPunctTokenizer().tokenize("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', 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', ',', 'Mr', '.', 'Jone', "'", 's', 'Orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop', '.']  


## 케라스 또한 토큰화 도구로서 text_to_word_sequence를 지원합니다. 이번에는 케라스로 토큰화를 수행해봅시다.
## 케라스의 text_to_word_sequence는 기본적으로 모든 알파벳을 소문자로 바꾸면서 온점이나 
## 컴마, 느낌표 등의 구두점을 제거합니다. 하지만 don't나 jone's와 같은 경우 아포스트로피는 보존하는 것을 볼 수 있습니다.
>from tensorflow.keras.preprocessing.text import text_to_word_sequence
>print(text_to_word_sequence("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", 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', 'mr', "jone's", 'orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop']


## 표준으로 쓰이고 있는 토큰화 방법 중 하나인 Penn Treebank Tokenization의 규칙에 대해서 소개하고, 토큰화의 결과를 보도록 하겠습니다.
## 규칙 1. 하이푼으로 구성된 단어는 하나로 유지한다.
## 규칙 2. doesn't와 같이 아포스트로피로 '접어'가 함께하는 단어는 분리해준다. 
>from nltk.tokenize import TreebankWordTokenizer
>tokenizer=TreebankWordTokenizer()
>text="Starting a home-based restaurant may be an ideal. it doesn't have a food chain or restaurant of their own."
>print(tokenizer.tokenize(text))
['Starting', 'a', 'home-based', 'restaurant', 'may', 'be', 'an', 'ideal.', 'it', 'does', "n't", 'have', 'a', 'food', 'chain', 'or', 'restaurant', 'of', 'their', 'own', '.']
반응형

+ Recent posts