토크나이징(Tokenizing)이란?
텍스트 데이터를 분석하거나 처리할 때 토크나이징(Tokenizing)은 매우 중요한 단계입니다. 토크나이징은 전체 텍스트를 원하는 구분 단위로 나누는 작업을 의미하며, 이를 통해 데이터를 보다 체계적이고 효율적으로 다룰 수 있습니다.
토크나이징의 유형
토크나이징은 나누는 단위에 따라 여러 가지 방식으로 진행할 수 있습니다. 대표적인 유형은 다음과 같습니다.
1. 문장 단위 토크나이징
텍스트를 문장 단위로 나누는 방식입니다. 일반적으로 문장의 끝을 나타내는 구두점(마침표, 느낌표, 물음표 등)을 기준으로 문장을 나눕니다.
예시:
Input : "Hello! How are you doing? I'm fine."
Output : ["Hello!", "How are you doing?", "I'm fine."]
2. 단어 단위 토크나이징
문장을 단어 단위로 나누는 방식입니다. 주로 공백이나 구두점을 기준으로 단어를 구분합니다. 영어의 경우 공백을 기준으로 쉽게 나눌 수 있지만, 한국어는 형태소 분석이 필요한 경우가 많습니다.
예시:
Input : "Friends, Romans, Countrymen, lend me your ears;."
Output : ["Friends", "Romans", "Countrymen", "lend", "me", "your", "ears"]
3. 형태소 단위 토크나이징
한국어나 일본어처럼 교착어의 경우에는 형태소 단위로 나누는 작업이 필요합니다.
형태소란 의미를 가지는 최소 단위로, 하나의 단어가 여러 형태소로 구성될 수 있습니다.
예를 들어, 한국어에서 "먹었다"는 "먹(동사 어근)" + "었(과거 시제)" + "다(종결 어미)"로 나눌 수 있습니다.
왜 토크나이징이 중요한가?
토크나이징은 텍스트 분석의 기초 단계로, 자연어 처리(NLP)의 핵심 역할을 합니다.
- 텍스트 분석: 단어 빈도 분석, 감성 분석, 주제 모델링 등에서 사용
- 정보 검색: 검색 엔진에서 문서를 효율적으로 색인하고 검색 결과를 개선
- 텍스트 생성: 챗봇, 자동 완성 등 자연어 생성 모델에 사용
NLTK란?
NLTK(Natural Language Toolkit)는 파이썬에서 자연어 처리(NLP)**를 쉽게 다룰 수 있게 해주는 라이브러리입니다.
텍스트 분석, 토크나이징, 형태소 분석, 감성 분석, 언어 모델링 등 다양한 NLP 작업을 지원합니다.
NLTK의 주요 기능
- 토크나이징(Tokenizing)
- 문장 단위 또는 단어 단위로 텍스트를 나눌 수 있습니다.
- 예: word_tokenize, sent_tokenize
- 품사 태깅(Part-of-Speech Tagging)
- 단어의 품사를 자동으로 태깅해줍니다.
- 예: pos_tag
- 정규 표현식 기반 토크나이저
- 정규 표현식을 사용하여 원하는 기준으로 토크나이징할 수 있습니다.
- 어간 추출(Stemming) 및 원형 복원(Lemmatization)
- 어간 추출: 단어의 어근만 추출 (예: running → run)
- 원형 복원: 문맥에 맞는 원형 복원 (예: running → run)
- 텍스트 전처리 및 정제
- 불용어(Stopwords) 제거
- 구두점 및 특수문자 제거
- 코퍼스(Corpus) 사용
- 말뭉치 데이터(Corpus)를 제공하여 학습에 활용 가능
- 예: 영화 리뷰, 뉴스 기사, 셰익스피어 작품 등 다양한 말뭉치 포함
NLTK 설치 및 사용 방법
NLTK는 파이썬 패키지 매니저인 pip를 사용하여 설치할 수 있습니다.
1. NLTK 설치
터미널 또는 명령 프롬프트에 아래 명령어를 입력하세요.
pip install nltk
2. NLTK 데이터 다운로드
NLTK는 다양한 언어 자원(코퍼스, 사전, 모델 등)을 제공합니다.
아래 코드를 실행하여 필요한 데이터를 다운로드하세요.
import nltk
nltk.download('all')
또는 필요한 데이터만 선택적으로 다운로드할 수 있습니다.
nltk.download('punkt') # 토크나이저
nltk.download('averaged_perceptron_tagger') # 품사 태깅
nltk.download('stopwords') # 불용어
nltk.download('wordnet') # 원형 복원
3. 간단한 예제
1. 단어 Tokenizing
예제
from nltk.tokenize import word_tokenize
text = "Friends, Romans, Countrymen, lend me your ears;."
print(word_tokenize(text))
결과
['Friends', ',', 'Romans', ',', 'Countrymen', ',', 'lend', 'me', 'your', 'ears', ';', '.']
2. 문장 단위 Tokenizing
예제
from nltk.tokenize import sent_tokenize
text = "Natural language processing (NLP) is a subfield of \
linguistics, computer science, and artificial intelligence \
concerned with the interactions between computers and human language, \
in particular how to program computers to process and analyze large \
amounts of natural language data. The goal is a computer capable of \
understanding the contents of documents, including the contextual \
nuances of the language within them. The technology can then accurately \
extract information and insights contained in the documents as well as categorize and organize the documents themselves."
print(sent_tokenize(text))
결과
['Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data.',
'The goal is a computer capable of understanding the contents of documents, including the contextual nuances of the language within them.',
'The technology can then accurately extract information and insights contained in the documents as well as categorize and organize the documents themselves.']
3. 품사 태깅 예제
예제
from nltk import pos_tag
text = "Hello! How are you doing today?"
tokens = word_tokenize(text)
tags = pos_tag(tokens)
print(tags)
결과
[('Hello', 'NN'), ('!', '.'), ('How', 'WRB'), ('are', 'VBP'), ('you', 'PRP'), ('doing', 'VBG'), ('today', 'NN'), ('?', '.')]
'AI > Basic NLP' 카테고리의 다른 글
NLTK를 활용한 N-GRAM 언어 모델 (0) | 2025.03.01 |
---|---|
scikit-learn을 활용한 One-hot Encoding (0) | 2025.02.27 |