본문 바로가기
Data/Data Analysis

[텍스트분석] 02. 텍스트 사전준비 (텍스트 전처리)

by 카프리썬 2021. 9. 4.
728x90

요즘 추천시스템이랑 텍스트분석쪽에 관심이 생겨서 책을 찾아보았다.

사실 이미 한번 프로젝트(?)로 수행했지만 훑어보고 간단하게 넘어간것 같아서..

다시한번 짚어보는 목적! 튼튼한 기본이 단단한 기초가 중요하니까! 

 

아래의 내용은 파이썬 머신러닝 완벽가이드의 책의 [8.텍스트분석] 읽고 정리한 내용입니다

 


이전에 살펴본 텍스트분석 프로세스에 따라 첫번째 단계인 텍스트사전준비! 를 살펴본다.

  1. 텍스트 사전준비 (텍스트 전처리) : 텍스트를 벡터로 만들기 전에 토큰화작업 
  2. 피쳐 벡터화/추출 : 가공된 텍스트에서 피쳐를 추출하고, 여기에 벡터값을 할당하는 작업 
  3. ML모델 수립 및 학습/예측/평가 : 피쳐 벡터화된 데이터세트에 ML모델을 적용해 학습/예측/평가 수행

 

텍스트 자체를 피쳐로 바로 만들수 없다.

그래서 사전에 텍스트를 가공하는 준비작업 즉, 텍스트 정규화작업이 필요하다.

 

텍스트 정규화작업이란?

텍스트를 머신러닝 알고리즘이나 NLP 애플리케이션에 입력데이터로 사용하기 위해 클렌징, 정제,토큰화, 어근화 등 

다양한 텍스트 데이터의 사전작업을 수행하는 것 

  • 클렌징 
  • 토큰화
  • 필터링/스톱워드제거/철자수정
  • stemming
  • Lemmatization

텍스트정규화 예시1 - 클렌징 작업

텍스트분석에 오히려 방해가 되는 불필요한 문자, 기호 등을 사전에 제거하는 작업

예를 들어 HTML,XML 태그나 특정기호 제거

 

텍스트정규화 예시2 - 텍스트 토큰화 작업

문장토큰화

문장의 마침표, 개행문자(줄바꿈) 등 문장의 마지막을 뜻하는 기호에 따라 문장을 분리하는 것이 일반적

또는 정규표현식에 따라 문장 토큰화도 가능하다. 

  • sent_tokenize() : 각각 '문장'기준으로 자동 토큰화 
  • 예시: 각 문장별로 짤라서 list에 담김
    from nltk import sent_tokenize
    import nltk
    nltk.download('punkt')
    
    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 whene you go to work, or go to church or pay your taxes."
    
    sentences = sent_tokenize(text=text_sample)
    print(type(sentences), len(sentences)) # <class 'list'> 3
    print(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 whene you go to work, or go to church or pay your taxes.'
      ]
     '''

단어토큰화 

문장을 단어로 토큰화

기본적으로 공백,콤마,마침표, 개행문자 등으로 단어를 분리하는 것

또는 정규표현식에 따라 단어 토큰화도 가능하다

일반적으로 각 문장이 가지는 시맨틱적인 의미가 중요한 요소로 사용될때 사용한다. 

  • word_tokenize() : 각가 '단어'를 기준으로 자동 토큰화
  • 예시
    from nltk import sent_tokenize
    from nltk import word_tokenize
    
    import nltk
    nltk.download('punkt')
    
    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 whene you go to work, or go to church or pay your taxes."
    #단어토큰화
    words = word_tokenize(text_sample)
    print(type(words), len(words)) #<class 'list'> 45
    print(words)
    '''
    ['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', 'whene', 'you', 'go', 'to',
     'work', ',', 'or', 'go', 'to', 'church', 'or', 'pay', 'your', 'taxes', '.']
    '''

텍스트정규화 예시3 - 스톱워드(불용어) 제거작업

분석에 큰 의미가 없는 단어를 지칭하고, 제거하는 작업

예를 들어 영어에서 is, the, a ,will 등 문장을 구성하는 필수문법 요소이지만 문맥적으론 큰 의미강 없는 단어들

 

언어별로 이런 스톱워드가 목록화되어 있다. 

영어에선 179개 정도 있는데, 한국어는 없다!!

import nltk
nltk.download('stopwords')

#stopwords 살펴보기
eng_stop = nltk.corpus.stopwords.words('english')
print("stopwords(eng) len: ", len(eng_stop)) #179개
print(eng_stop[:20])

# ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his']

한국어 같은 경우 스톱워드(불용어)를 지정해서 제거해줘야햔다..

#한국어 stopwords 지정하기
example = "하 그런데 NTLK는 한국어 불용어 데이터를 제공하지 않습니다. \
           그냥 토큰화 단계에서 필요없는 조사, 접속사를 제거하면 되기 때문입니다."
stop_words = "하 그런데 그냥 되기 때문입니다"

word_tokens = word_tokenize(example)
stop_words=stop_words.split(' ')

result = []
for w in word_tokens:
    if w not in stop_words:
        result.append(w) # 불용어가 아닌 단어들만 사용한다
#stopword제거된상태        
print(result)

 

텍스트정규화 예시4 - Stemming과 Lemmatization

이건 영어의 경우에만 해당하는 것 같은데,

영어문법에서 같은 의미의 단어니지만 과거/현재/진행형/3인칭 단수여부 등에 따라 단어가 변하기 때문에

이걸 구분해서 단어를 토큰화하는 방식이다. 

 

나는 한글 텍스트분석을 해보고 싶으니까 이건 패스할래ㅠㅠ

 

 

반응형

$(document).ready(function() { var $toc = $("#toc"); $toc.toc({content: ".tt_article_useless_p_margin", headings: "h2,h3,h4"}); });