NLP, 텍스트 분석

  • Natural Language Processing : 기계가 인간의 언어를 이해하고 해석하는데 중점. 기계번역, 질의응답시스템
  • 텍스트 분석 : 비정형 텍스트에서 의미있는 정보를 추출하는 것에 중점
  • NLP는 텍스트 분석을 향상하게 하는 기반 기술
  • NLP와 텍스트 분석의 근간에는 머신러닝이 존재. 과거 언어적인 룰 기반 시스템에서 텍스트 데이터 기반으로 모델을 학습하고 예측
  • 텍스트 분석은 머신러닝, 언어 이해, 통계 등을 활용한 모델 수립, 정보 추출을 통해 인사이트 및 예측 분석 등의 분석 작업 수행
    • 텍스트 분류 : 신문기사 카테고리 분류, 스팸 메일 검출 프로그램. 지도학습
    • 감성 분석 : 감정/판단/믿음/의견/기분 등의 주관적 요소 분석. 소셜미디어 감정분석, 영화 리뷰, 여론조사 의견분석. 지도학습, 비지도학습
    • 텍스트 요약 : 텍스트 내에서 중요한 주제나 중심 사상을 추출. 토픽 모델링
    • 텍스트 군집화와 유사도 측정 : 비슷한 유형의 문서에 대해 군집화 수행. 비지도 학습

텍스트 전처리

1. 텍스트 정규화

  • 클렌징 : 분석에 방해되는 불필요한 문자, 기호를 사전에 제거. HTML, XML 태그나 특정 기호
  • 토큰화 : 문서에서 문장을 분리하는 문장 토큰화와 문장에서 단어를 토큰으로 분리하는 단어 토큰화
  • filering / stopword 제거 / 철자 수정 : 분석에 큰 의미가 없는 단어를 제거
  • Stemming, Lemmatization : 문법적 또는 의미적으로 변화하는 단어의 원형을 찾음
    • Stemming은 원형 단어로 변환 시 일반적인 방법을 적용하거나 더 단순화된 방법을 적용
    • Lemmatization이 Stemming 보다 정교하며 의미론적인 기반에서 단어의 원형을 찾음

1) 문장 토큰화(sent tokenize)

  • 마침표, 개행문자(\n), 정규표현식
import nltk
nltk.download('punkt')

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(sentences)
print(type(sentences), len(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 when you go to work, or go to church or pay your taxes.']
<class 'list'> 3

2) 단어 토큰화(word_tokenize)

  • 공백, 콤마, 마침표, 개행문자, 정규표현식
from nltk import word_tokenize 

sentence = 'The Matrix is everywhere its all around us, here even in this room.'
words = word_tokenize(sentence)
print(words)
print(type(words),len(words))

#출력
['The', 'Matrix', 'is', 'everywhere', 'its', 'all', 'around', 'us', ',', 'here', 'even', 'in', 'this', 'room', '.']
<class 'list'> 15

3) 문서에 대해서 모든 단어를 토큰화

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(word_tokens)
print(type(word_tokens), len(word_tokens))    

#출력
[['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', '.']]
<class 'list'> 3

2. stopword 제거

  • is, the, a, will 과 같이 문맥적으로 큰 의마가 없는 단어를 제거

1) nltk의 english stopwords 갯수 확인

import nltk
nltk.download('stopwords')

print('영어 stop words 갯수:', len(nltk.corpus.stopwords.words('english')))
print(nltk.corpus.stopwords.words('english')[:20])

#출력
영어 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']

2) stopwords 필터링을 통한 제거

import nltk
stopwords = nltk.corpus.stopwords.words('english')
all_tokens =[]
for sentence in word_tokens:
    filtered_words = []
    for word in sentence:
        word = word.lower()
        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(LancasterStemmer)

  • 문법적 또는 의미적으로 변화하는 단어의 원형을 찾음
rom 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

Lemmatization(WordNetLemmatizer)

  • 정확한 원형 단어 추출을 위해 단어의 품사를 입력
import nltk
nltk.download('wordnet')

from nltk.stem.wordnet 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

results matching ""

    No results matching ""