본문 바로가기

텍스트 마이닝

텍스트 전처리 (2)

반응형

2.2 토큰화

# 필요한 nltk 라이브러리 다운로드
import nltk
nltk.download('punkt')
nltk.download('webtext')
nltk.download('wordnet')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')


"""
[nltk_data] Downloading package punkt to /root/nltk_data...
[nltk_data]   Unzipping tokenizers/punkt.zip.
[nltk_data] Downloading package webtext to /root/nltk_data...
[nltk_data]   Unzipping corpora/webtext.zip.
[nltk_data] Downloading package wordnet to /root/nltk_data...
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data]   Unzipping corpora/stopwords.zip.
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data]     /root/nltk_data...
[nltk_data]   Unzipping taggers/averaged_perceptron_tagger.zip.
True
"""

2.2.1 문장 토큰화

  • 문장을 원하는 단위로 나누는 작업
  • 여러 문장으로 이루어진 텍스트를 각 문장으로 나누는 것
  • nltk의 sent_tokenize 사용
para = "Hello everyone. It's good to see you. Let's start our text mining class!"

from nltk.tokenize import sent_tokenize
print(sent_tokenize(para))

## ['Hello everyone.', "It's good to see you.", "Let's start our text mining class!"]
paragraph_french = """Je t'ai demandé si tu m'aimais bien, Tu m'a répondu non. 
Je t'ai demandé si j'étais jolie, Tu m'a répondu non. 
Je t'ai demandé si j'étai dans ton coeur, Tu m'a répondu non."""

import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/french.pickle')
print(tokenizer.tokenize(paragraph_french))

## ["Je t'ai demandé si tu m'aimais bien, Tu m'a répondu non.", "Je t'ai demandé si j'étais jolie, Tu m'a répondu non.", "Je t'ai demandé si j'étai dans ton coeur, Tu m'a répondu non."]
para_kor = "안녕하세요, 여러분. 만나서 반갑습니다. 이제 텍스트마이닝 클래스를 시작해봅시다!"
print(sent_tokenize(para_kor))

## ['안녕하세요, 여러분.', '만나서 반갑습니다.', '이제 텍스트마이닝 클래스를 시작해봅시다!']

2.2.2 단어 토큰화

  • 대상이 되는 텍스트를 단어 단위로 분리하는 작업
  • NLTK에서는 word_tokenize로 단어 토큰화 가능
  • 단어 토큰화를 위해 반드시 문장 토큰화를 수행할 필요 없음
from nltk.tokenize import word_tokenize
print(word_tokenize(para))

## ['Hello', 'everyone', '.', 'It', "'s", 'good', 'to', 'see', 'you', '.', 'Let', "'s", 'start', 'our', 'text', 'mining', 'class', '!']
print(word_tokenize(para_kor))

## ['안녕하세요', ',', '여러분', '.', '만나서', '반갑습니다', '.', '이제', '텍스트마이닝', '클래스를', '시작해봅시다', '!']
  • 한국어 텍스트를 정확하게 토큰화 하기 위해서는 영어와는 다른 방법이 필요함

2.2.3 정규표현식을 이용한 토큰화

  • NLTK를 쓰지 않고 다양한 조건에 따라 토큰화 가능
  • 정규표현식을 익혀야 함
import re
re.findall("[abc]", "How are you, boy?")

## ['a', 'b']
re.findall("[0123456789]", "3a7b5c9d")

## ['3', '7', '5', '9']
re.findall("[\w]", "3a 7b_ '.^&5c9d")

## ['3', 'a', '7', 'b', '_', '5', 'c', '9', 'd']
re.findall("[_]+", "a_b, c__d, e___f")

## ['_', '__', '___']
re.findall("[\w]+", "How are you, boy?")

## ['How', 'are', 'you', 'boy']
re.findall("[o]{2,4}", "oh, hoow are yoooou, boooooooy?")

## ['oo', 'oooo', 'oooo', 'ooo']
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer("[\w']+") #regular expression(정규식)을 이용한 tokenizer
#단어단위로 tokenize \w:문자나 숫자를 의미 즉 문자나 숫자 혹은 '가 반복되는 것을 찾아냄
print(tokenizer.tokenize("Sorry, I can't go there."))
# can't를 하나의 단어로 인식

## ['Sorry', 'I', "can't", 'go', 'there']
tokenizer = RegexpTokenizer("[\w]+") 
print(tokenizer.tokenize("Sorry, I can't go there."))

## ['Sorry', 'I', 'can', 't', 'go', 'there']
text1 = "Sorry, I can't go there."
tokenizer = RegexpTokenizer("[\w']{3,}") 
print(tokenizer.tokenize(text1.lower()))

## ['sorry', "can't", 'there']

2.2.4 노이즈와 불용어 제거

  • 불용어: 실제 사용되는 단어이지만 분석에는 별 필요가 없는 단어
  • 빈도가 너무 적거나 혹은 반대로 빈도가 너무 많아서 별 필요가 없는 단어들
  • 분석의 목표 관점에서 볼 때 필요 없는 단어들
from nltk.corpus import stopwords #일반적으로 분석대상이 아닌 단어들
english_stops = set(stopwords.words('english')) #반복이 되지 않도록 set으로 변환

text1 = "Sorry, I couldn't go to movie yesterday."

tokenizer = RegexpTokenizer("[\w']+")
tokens = tokenizer.tokenize(text1.lower()) #word_tokenize로 토큰화

result = [word for word in tokens if word not in english_stops] #stopwords를 제외한 단어들만으로 list를 생성
print(result)

## ['sorry', 'go', 'movie', 'yesterday']
print(english_stops) #nltk가 제공하는 영어 stopword를 확인

## {'d', 'hasn', "couldn't", 'my', 'are', 'both', 'nor', 'through', 'ma', "won't", 'did', "you'd", 'up', 'in', 'with', 'doesn', "shan't", 'ourselves', 'don', 'shan', 'himself', "hasn't", 'on', "weren't", 'some', "mustn't", 'that', 'for', 'out', 'more', 'few', 'had', "mightn't", 'does', 'mustn', 'll', 'she', 'most', 'all', "hadn't", 'them', 'needn', 'if', "wasn't", 'so', 'been', 'not', 'y', 'what', "don't", 'as', "didn't", 'is', 'during', 'off', 'their', "should've", 'very', 'over', "you'll", 'doing', "isn't", 'own', 'until', 'by', 'yourself', 'to', 'under', 'wouldn', 'have', 'having', 'an', 'being', 'be', 'when', 'myself', 'about', 'he', 'where', 'o', 'before', 'weren', 'from', "it's", 't', "doesn't", 'who', 'your', 'here', 'his', 'how', 'yours', 'same', 'just', 'i', "you're", 'theirs', 'mightn', 'we', 'you', 'then', "you've", 'was', 'ours', 'will', 'why', "shouldn't", 'this', 'while', "haven't", 'they', 'into', 'too', 'at', 'yourselves', 're', 'there', 'him', 'won', 'herself', 'whom', 'than', 'her', 'now', 'because', 'down', 'aren', 'further', 'our', 'a', 'any', 'do', 'and', 'shouldn', 'only', 'its', "aren't", 'haven', 'can', 'itself', 'hadn', 'but', 'other', 've', 'should', 'ain', 'couldn', 'isn', 'it', 'no', 'hers', 'those', 'the', "she's", 'themselves', 'again', 'below', 's', 'such', "needn't", 'above', 'each', 'were', 'which', 'didn', 'after', 'm', "that'll", 'of', 'between', 'me', 'has', 'am', 'or', 'once', 'against', 'these', 'wasn', "wouldn't"}
#자신만의 stopwords를 만들고 이용
#한글처리에서도 유용하게 사용할 수 있음
my_stopword = ['i', 'go', 'to'] #나만의 stopword를 리스트로 정의
result = [word for word in tokens if word not in my_stopword] 
print(result)

## ['sorry', "couldn't", 'movie', 'yesterday']

 

 

 

 

 

※ 해당 내용은 <파이썬 텍스트 마이닝 완벽 가이드>의 내용을 토대로 학습하며 정리한 내용입니다.

반응형

'텍스트 마이닝' 카테고리의 다른 글

텍스트 전처리 (4)  (0) 2023.06.21
텍스트 전처리 (3)  (0) 2023.06.20
텍스트 전처리 (1)  (0) 2023.06.18
텍스트 마이닝 기초 (2)  (0) 2023.06.17
텍스트 마이닝 기초 (1)  (0) 2023.06.16