Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

Silver bullet

한글 텍스트 데이터 전처리 본문

AI/AI

한글 텍스트 데이터 전처리

밀크쌀과자 2024. 7. 2. 16:05

The process of data analysis for text data

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

2. Tokenize (형태소 분석)  POS Tagging (Part-of-speech, 품사 표시)  Stopwords 제거 (불용어 제거)

3. 단어 개수 카운팅 & 단어 사전 생성  단어 사전 기반 데이터 시각화  (+ 머신러닝/딥러닝 모델 적용)

1. konlpy 테스트

# Konlpy 라이브러리가 정상적으로 작동하는지 확인합니다.
from konlpy.tag import Okt

tokenizer = Okt()
tokens = tokenizer.pos("아버지 가방에 들어가신다.", norm=True, stem=True)
print(tokens)

 

pickle 파일 사용법

# import os, pickle 

# # 파이썬 변수를 pickle 파일로 저장하는 방법 
with open('raw_pos_tagged.pkl', 'wb') as f:
     pickle.dump(raw_pos_tagged, f) 

# # pickle 파일로부터 파이썬 변수를 불러오는 방법 
with open('raw_pos_tagged.pkl','rb') as f:
     data = pickle.load(f)
# # -> "ran out of input" 문제 발생 시 아래 코드로 대신 실행

# data = [] 
# if os.path.getsize('raw_pos_tagged.pkl') > 0:      
#     with open('raw_pos_tagged.pkl', "rb") as f:
#         unpickler = pickle.Unpickler(f)
#         data = unpickler.load()
# data

 

2. 크롤링 데이터 전처리

import numpy as np
import pandas as pd

df = pd.read_excel('result_220202_1834.xlsx')
df.head()

articles = df['Article'].tolist() # 리스트로 변환
len(articles)

articles = ' '.join(articles) # 리스트의 아이템들을 특정한 문자를 기준으로 이어 붙이기
articles[:1000]

len(articles)

 

2-1. 단어 정규화 및 어근화, 품사 태깅

pos 함수를 진행하는데 커널이 죽는 경우 -> 이모티콘이 포함되어 있을수도 있음. -> 파이썬 이모티콘 제거

# input data 에 품사를 태깅(tagging)합니다.
# 이 때, stem 및 norm 옵션의 기능은 다음과 같습니다.

# norm == 정규화(normalization)
# 한국어를 처리하는 예시입니닼ㅋㅋㅋ -> 한국어를 처리하는 예시입니다ㅋㅋ

# stem == 어근화(stemming)
# 한국어를 처리하는 예시입니다 ㅋㅋ -> 한국어Noun, 를Josa, 처리Noun, 하다Verb, 예시Noun, 이다Adjective, ㅋㅋKoreanParticle


# pos 함수를 진행하는데 커널이 죽는 경우 -> 이모티콘이 포함되어 있을수도 있음. -> 파이썬 이모티콘 제거
from konlpy.tag import Okt

tokenizer = Okt()
raw_pos_tagged = tokenizer.pos(articles, norm=True, stem=True) # POS Tagging 토큰화, 품사 정보 한번에
raw_pos_tagged

2-2. 단어 등장 빈도 카운팅

# 정규화 및 어근화를 마치고 품사 태깅까지 마친 상태에서,
# 조사, 어미, 구두점을 제외한 나머지 단어들을 모두 word_cleaned 리스트에 담습니다.
# 이 때에는 여러번 나온 단어들도 복수 허용되어 여러번 리스트에 담기게 됩니다.

# 유의미한 의미를 갖고 있지 않은 단어를 제외할 수 있습니다.
del_list = ['하다', '있다', '되다', '이다', '돼다', '않다', '그렇다', '아니다', '이렇다', '그렇다', '어떻다'] 

word_cleaned = []
for word in raw_pos_tagged: #  ('서울', 'Noun'),
    if word[1] not in ["Josa", "Eomi", "Punctuation", "Foreign"]: # Foreign == ”, “ 와 같이 제외되어야할 항목들
        if (len(word[0]) != 1) & (word[0] not in del_list): # 한 글자로 이뤄진 단어들을 제외 & 원치 않는 단어들을 제외
            word_cleaned.append(word[0])
        
word_cleaned
from collections import Counter
result = Counter(word_cleaned)
word_dic = dict(result)
word_dic
word_dic.items()

# lambda 함수를 활용하여,
# 앞서 만든 dict를 item 단위(tuple)로 꺼내어, tuple(x)의 value(x[1])를 기준으로 하여 내림차순(reverse=True) 정렬합니다.

sorted_word_dic = sorted(word_dic.items(), key=lambda x:x[1], reverse=True)
sorted_word_dic

# 내림차순 정렬된 단어 중 상위 50개를 살펴보면 다음과 같습니다.

# ('데이터', 538),
for word, count in sorted_word_dic[:50]:
    print("{0}({1})".format(word, count), end=" ")