[Python 머신러닝] 08-2 텍스트 사전 준비(텍스트 전처리) - 텍스트 정규화
텍스트 분석
텍스트 사전 준비(텍스트 전처리) - 텍스트 정규화
클렌징(Cleansing)
텍스트에서 분석에 오히려 방해가 되는 불필요한 문자, 기호 등을 사전에 제거하는 작업이다.
예를 들어 HTML, XML 태그나 특정 기호 등을 사전에 제거한다.
텍스트 토큰화(Text Tokenization)
문서에서 문장을 분리하는 문장 토큰화와 문장에서 단얼르 토큰으로 분리하는 단어 토큰화로 나눌 수 있다.
-
문장 토큰화
문장의 마침표(.), 개행문자(\n) 등 문장의 마지막을 뜻하는 기호에 따라 분리하는 것이 일반적이다.
또한 정규 표현식에 따른 문장 토큰화도 가능하다.#### <실습>실습>
from nltk import sent_tokenize 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 when you go to work, or go to church or pay your taxes.' sentences = sent_tokenize(text=text_sample) print(type(sentences),len(sentences)) print(sentences)<class 'list'> 3 ['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 when you go to work, or go to church or pay your taxes.'] -
단어 토큰화
기본적으로 공백, 콤마(,), 마침표(.), 개행문자 등으로 분리한다.
정규 표현식을 이용해 다양한 유형으로 토큰화를 수행할 수 있다.#### <실습>실습>
from nltk import word_tokenize sentence = "The Matrix is everywhere its all around us, here even in this room." words = word_tokenize(sentence) print(type(words), len(words)) print(words)<class 'list'> 15 ['The', 'Matrix', 'is', 'everywhere', 'its', 'all', 'around', 'us', ',', 'here', 'even', 'in', 'this', 'room', '.']여러 문장들에 대한 단어 토큰화
from nltk import word_tokenize, sent_tokenize #여러개의 문장으로 된 입력 데이터를 문장별로 단어 토큰화 만드는 함수 생성 def tokenize_text(text): # 문장별로 분리 토큰 sentences = sent_tokenize(text) # 분리된 문장별 단어 토큰화 word_tokens = [word_tokenize(sentence) for sentence in sentences] return word_tokens #여러 문장들에 대해 문장별 단어 토큰화 수행. word_tokens = tokenize_text(text_sample) print(type(word_tokens),len(word_tokens)) print(word_tokens)<class 'list'> 3 [['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', 'when', 'you', 'go', 'to', 'work', ',', 'or', 'go', 'to', 'church', 'or', 'pay', 'your', 'taxes', '.']]
N-gram
- 문장을 개별 단어 별로 하나씩 토큰화할 경우 문맥적인 의미는 무시될 수 밖에 없다.
이러한 문제를 조금이라도 해결해 보고자 도입된 것이 n-gram이다. - n-gram은 연속된 n개의 단어를 하나의 토큰화 단위로 분리해 내는 것이다.
n개 단어 크기 윈도우를 만들어 문장의 처음부터 오른쪽으로 움직이면서 토큰화를 수행한다. - 예를 들어 “Agent Smith knocks the door”를 2-gram(bigram)으로 만들면 (Agent, Smith), (Smith, knocks), (knocks, the), (the, door)와 같이 연속적으로 2개의 단어들을 순차적으로 이동하면서 단어들을 토큰화한다.
<실습>실습>
from nltk import ngrams
sentence = "The Matrix is everywhere its all around us, here even in this room."
words = word_tokenize(sentence)
all_ngrams = ngrams(words, 2)
ngrams = [ngram for ngram in all_ngrams]
print(ngrams)
[('The', 'Matrix'), ('Matrix', 'is'), ('is', 'everywhere'), ('everywhere', 'its'), ('its', 'all'), ('all', 'around'), ('around', 'us'), ('us', ','), (',', 'here'), ('here', 'even'), ('even', 'in'), ('in', 'this'), ('this', 'room'), ('room', '.')]
스톱 워드 제거
불필요한 단어나 분석에 큰 의미가 없는 단어(a, the, is, will 등)를 제거한다.
<실습>실습>
import nltk
nltk.download('stopwords')
[nltk_data] Downloading package stopwords to
[nltk_data] C:\Users\AppData\Roaming\nltk_data...
[nltk_data] Unzipping corpora\stopwords.zip.
True
print('영어 stop words 갯수:',len(nltk.corpus.stopwords.words('english')))
print(nltk.corpus.stopwords.words('english')[:40])
영어 stop words 갯수: 179
['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this']
import nltk
stopwords = nltk.corpus.stopwords.words('english')
all_tokens = []
# 위 예제의 3개의 문장별로 얻은 word_tokens list 에 대해 stop word 제거 Loop
for sentence in word_tokens:
filtered_words=[]
# 개별 문장별로 tokenize된 sentence list에 대해 stop word 제거 Loop
for word in sentence:
#소문자로 모두 변환합니다.
word = word.lower()
# tokenize 된 개별 word가 stop words 들의 단어에 포함되지 않으면 word_tokens에 추가
if word not in stopwords:
filtered_words.append(word)
all_tokens.append(filtered_words)
print(all_tokens)
[['matrix', 'everywhere', 'around', 'us', ',', 'even', 'room', '.'], ['see', 'window', 'television', '.'], ['feel', 'go', 'work', ',', 'go', 'church', 'pay', 'taxes', '.']]
Stemming과 Lemmatization
문법적 또는 의미적으로 변화하는 어근(단어 원형)을 추출한다.
Lemmatization이 Stemming보다 정교하고 의미론적 기반에서 단어 원형을 찾아준다.
<실습>실습>
from nltk.stem import LancasterStemmer
stemmer = LancasterStemmer()
print(stemmer.stem('working'),stemmer.stem('works'),stemmer.stem('worked'))
print(stemmer.stem('amusing'),stemmer.stem('amuses'),stemmer.stem('amused'))
print(stemmer.stem('happier'),stemmer.stem('happiest'))
print(stemmer.stem('fancier'),stemmer.stem('fanciest'))
work work work
amus amus amus
happy happiest
fant fanciest
from nltk.stem import WordNetLemmatizer
lemma = WordNetLemmatizer()
print(lemma.lemmatize('amusing','v'),lemma.lemmatize('amuses','v'),lemma.lemmatize('amused','v'))
print(lemma.lemmatize('happier','a'),lemma.lemmatize('happiest','a'))
print(lemma.lemmatize('fancier','a'),lemma.lemmatize('fanciest','a'))
amuse amuse amuse
happy happy
fancy fancy