본문으로 바로가기

" 자연어처리(NLP) _Overall Process "

1. 텍스트 데이터를 str 자료형으로 준비

=================================

[Preprocessing Text Data]

2. Tokenize (형태소 분석)

3. POS Tagging (Part-of-speech, 품사 표시)

4. Stopwords(불용어) 제거

+ Lemmatizing (기본 사전형으로 변환)

 

=================================

[Text Data Exploration]

5. 단어 갯수 카운팅 & 단어 사전 생성

6. 단어 사전 기반 데이터 시각화

7. 머신러닝/딥러닝 모델 적용

+ 문맥상 유사한 단어 출력하기

+ 텍스트의 collocation(연어) 출력하기

 


[Preprocessing Text Data]

 

1. 텍스트 데이터를 str 자료형으로 준비

2. Tokenize (형태소 분석)

3. POS Tagging (Part-of-speech, 품사 표시)

4. Stopwords(불용어) 제거

import nltk
from nltk.corpus import stopwords
from collections import Counter
# Stopwords 준비
stop_words = stopwords.words("english")
# stopWords.append('.', ',')

'''1. 텍스트 데이터를 str 자료형으로 준비'''
file = open('darkknight.txt', 'r', encoding="utf-8") 
# 리뷰 str 변수들을 담고 있는 리스트
lines = file.readlines()  # readlines 함수로 한 행의 텍스트 파일의 내용을 읽어 리스트로 저장한다


'''2. Tokenize'''
'''4. Stopwords 제거'''
# 2. POS tagging과 3. Stopwords 제거는 순서를 자유롭게 조정 가능
tokens = []
for line in lines:  # for문을 통해 각 줄에 접근한다
    tokenized = nltk.word_tokenize(line)   #형태소들이 담긴 list
    for token in tokenized:   # 형태소 str 1건
        if token.lower() not in stop_words:
            tokens.append(token)


'''3. POS Tagging'''
tags = nltk.pos_tag(tokens)
# 명사 종류만 모으고 싶다면
wordList = []
for word, tag in tags:  # for 문을 통해 각각의 (단어, 태그) 쌍에 접근
    if tag in ['NN', 'NNS', 'NNP', 'NNPS']:  # 또는 if tag.startswith('N'):
        wordList.append(word.lower())

 

+ Lemmatizing (기본 사전형으로 변환)

추가로 할 수 있는 전처리로는 Lemmatizing이 있다.

- 'cats'를 'cat'으로 변환해주는 등의 사전형으로 변환시키는 작업

- 한글에서는 Lemmatizing 대신 Normalization을 사용한다.

   - '안녕하세욬ㅋㅋ' -> '안녕하세요'

# WordNetLemmatizer 객체 생성
lemmatizer = nltk.wordnet.WordNetLemmatizer()

print(lemmatizer.lemmatize("better"))            # >better
print(lemmatizer.lemmatize("better", pos="a"))   # >good

# 더 깔끔한 사전형을 원한다면 pos 정보를 추가로 입력해주면 된다

 

- 1번, 2번, 4번, Lemmatizing 순서로 실행한 코드:

stop_words = stopwords.words("english")
stop_words.append(',', '.')

file = open('moviereview.txt', 'r', encoding='utf-8')
lines = file.readlines() 

sentence = lines[1] 
tokens = nltk.word_tokenize(sentence)  

# for문을 통해 stopwords 제거와 lemmatization을 수행한다
lemmas = []  # lemmatize한 결과를 담기 위한 리스트를 생성한다
for token in tokens:  
    if token.lower() not in stop_words:
        lemmas.append(lemmatizer.lemmatize(token))   # 품사 정보(pos)를 넣어주면 더 정확해짐

print('Lemmas of : ' + sentence)  # lemmatize한 결과를 출력한다
print(lemmas)

 

 

+ 정규표현식(re)으로 Stopwords 지정하기

'''
Regular Expression

# '^[a-zA-Z]+' <- + : one or more ('a', 'airplane')
# '^[a-zA-Z]*' <- * : zero or more ('a', 'airplane', '')
# '^[a-zA-Z]?' <- ? : zero or one ('a', 'B', '')

# \s : whitespace 문자 [ \t\n\r\f\w]   <->   \S
# \w : alphanumeric                    <->   \W : anti-alphanumeric


^[a-zA-Z]+
: a-zA-Z(영문 대소문자)로 시작되며 a-zA-Z 중에 무엇이든 하나 이상으로 이루어져야 한다

^[a-zA-Z0-9가-힣]+
- re.match('^[a-zA-Z0-9가-힣]+', '안녕 하세요')   # > 공백이 있기에 return 안됨

'''
import re
# re.compile() : python에게 전해주는 역할
# re.match('정규표현식', token) : token이 해당 '정규표현식'에 매치되는지 검색
# re.split() : 정규표현식 기준으로 문자열 분리하여 리스트로 리턴
# re.findall() : 문자열에서 정규 표현식과 매치되는 모든 경우의 문자열 찾아 리스트로 리턴
# re.sub() : substitute, 문자열에서 정규표현식과 일치하는 부분에 대해 다른 문자열로 대체

stop_words = stopwords.words("english")
stop_words.append('else')

file = open('darkknight.txt', 'r', encoding="utf-8")
lines = file.readlines()

tokens = []
for line in lines:
    tokenized = nltk.word_tokenize(line)  
    for token in tokenized:
        if token.lower() not in stop_words: 
            if re.match('^[a-zA-Z]+', token):   # 특수 기호에 해당하지 않을 경우,
                tokens.append(token)

[Text Data Exploration]

5. 단어 갯수 카운팅 & 단어 사전 생성

6. 단어 사전 기반 데이터 시각화

7. 머신러닝/딥러닝 모델 적용

'''5. 단어 갯수 카운팅 & 단어 사전 생성'''
counts = Counter(wordList)  # 각 명사의 숫자를 센 결과를 dict형으로 저장
print(counts.most_common(10))
print(counts)


'''6. 단어 사전 기반 데이터 시각화: 2번 후 바로 가능'''
corpus = nltk.Text(tokens)
plt.figure(figsize=(10, 3), dpi=100) 
plt.title('Top 25 Words',fontsize=30)
corpus.plot(25)

 

+ 문맥상 유사한 단어 출력하기

+ 텍스트의 Collocation(연어) 출력하기

file = open('darkknight.txt', 'r', encoding="utf-8")  # 읽기 형식('r')로 지정하고 인코딩은 'utf-8'로 설정한다
lines = file.readlines()  # readlines 함수로 텍스트 파일의 내용을 읽어 리스트로 저장한다

tokens = []
for line in lines:  # for문을 통해 각 줄에 접근한다
    tokenized = nltk.word_tokenize(line)  # 각 줄을 tokenize한다
    for token in tokenized: # 각 Token이
        if token.lower() not in stop_words: # Stopwords 리스트에 포함되어 있지 않으며,
            if re.match('^[a-zA-Z]+', token): # 특수 기호에 해당하지 않을 경우,
                tokens.append(token) # Token list 에 추가해준다.

corpus = nltk.Text(tokens)
# 유사한 단어들 출력
print('Similar words : ')
corpus.similar('batman')


# 텍스트 Collocation(연어) 출력
# 함께 위치한 단어들
print('Collocation')
corpus.collocations()