Colab으로 하루에 하나씩 딥러닝

자연어 전처리_2.전처리_1) 토큰화 본문

딥러닝_개념

자연어 전처리_2.전처리_1) 토큰화

Elleik 2022. 12. 8. 23:08
728x90

토큰화

  • 주어진 텍스트를 단어 / 문자 단위로 자르는 것
  • 문장 토큰화 / 단어 토큰화로 구분

문장 토큰화

  • 마침표(,), 느낌표(!), 물음표(?) 등 문장의 마지막을 뜻하는 기호에 따라 분리
### 문장 토큰화

import nltk
nltk.download('punkt')
from nltk import sent_tokenize
text_sample = """Natural Language Processing, or NLP, is the process of extracting the meaning, or intent, behind human language. 
              In the field of Conversational artifical intelligence(AI), NLP allows machine and applications to understand the intent of
              human language inputs, and then generate responses, resulting in a natural conversation flow."""
tokenized_sentences = sent_tokenize(text_sample)
print(tokenized_sentences)

 

문장 토큰화 결과


단어 토큰화

  • 띄어쓰기를 기준으로 문장을 구분
  • 한국어는 띄어쓰기만으로 토큰을 구분하기 어려워서 KoNLPy를 사용
### 단어 토큰화

from nltk import word_tokenize
sentence = "This book is for deep learning learners"
words = word_tokenize(sentence)
print(words)

단어 토큰화 결과

### 아포스트로피가 포함된 문장에서 단어 토큰화

from nltk.tokenize import WordPunctTokenizer
sentence = "it's nothing that you don't already know except most people aren't aware of how their inner world works."
words = WordPunctTokenizer().tokenize(sentence)
print(words)

 

아포스트로피가 포함된 문장에서 단어 토큰화 결과

### 케라스를 이용한 단어 토큰화

import tensorflow
from tensorflow.keras.preprocessing.text import text_to_word_sequence
sentence = "it's nothing that you don't already know except most people aren't aware of how their inner world works."
word = text_to_word_sequence(sentence)
print(words)

케라스를 이용한 단어 토큰화 결과


한글 토큰화 예제

  • https://github.com/e9t/nsmc 의 ratings_train.txt 데이터 파일 사용
  • 한글 형태소 분석을 위해 오픈 소스 한글 형태소 분석기(Twitter(Okt)) 사용
  • 코랩에서 원활하게 사용하기 위하여 
### 코랩 사용 전 준비 (1.드라이브 마운트하기)

from google.colab import drive
drive.mount('/content/drive')
### 코랩 사용 전 준비 (2.github 클론하기)

%cd /content

!git clone https://github.com/e9t/nsmc.git
### 라이브러리 호출 및 데이터셋 준비

import csv
import konlpy
import gensim

from konlpy.tag import Okt
from gensim.models import word2vec

f = open('/content/nsmc/ratings_train.txt','r', encoding='utf-8')	
rdr = csv.reader(f, delimiter='\t')
rdw = list(rdr)
f.close()
### 오픈 소스 한글 형태소 분석기 호출

twitter = Okt()

result = []
for line in rdw:  # 텍스트 한 줄씩 처리
  malist = twitter.pos(line[1],norm=True, stem=True) # 형태소 분석
  r = []
  for word in malist:
    if not word[1] in ["Josa", "Eomi","Punctuation"]: # 조사, 어미, 문장 부호는 제외하고 처리
      r.append(word[0])
  rl = (" ".join(r)).strip()  # 형태소 사이에 공백 " "을 넣고, 양쪽 공백은 삭제
  result.append(rl)
  print(rl)

형태소 분석 결과, 데이터가 많기 때문에 16분 정도 시간 소요됨

### 형태소 저장

with open("NaverMovie.nlp", 'w', encoding='utf-8') as fp:
  fp.write("\n".join(result))
### Word2Vec 모델 생성 

mData = word2vec.LineSentence("NaverMovie.nlp")
mModel = word2vec.Word2Vec(mData, size=200, window=10, hs=1, min_count=2, sg=1)
mModel.save("NaverMovie.model") # 모델 저장

모델 저장 후 파일 경로

출처: 서지영, 『딥러닝 텐서플로 교과서』, 길벗(2022)