728x90
1.정제(Cleaning)
문장을 토큰화하기 이전 우리는 문장을 한번 Cleaning하는 과정을 거쳐야한다.
그렇지 않으면 아래처럼 '.', '?' 같은 목적에 맞지않는 불필요한 요소들이 같이 토큰화된다.
['한겨울', '밤', '의', '하늘', '은', '차갑고', '맑았다', '.', '별빛', '은', '검은', '
캔버스', '위', '에', '수', '를', '놓듯', '흩어져', '있었고', ',', '달', '은', '마치', '은빛', '으로', '도금', '된', '보석', '처럼', '찬란하게', '빛났다', '.', '바람', '은', '나뭇가지', '사이', '를', '스치며', '낮게', '울렸고', ',', '얼음', '처럼', '차가운', '공기', '는', '숨', '을', '쉴', '때', '마다', '뺨', '을', '얼렸다', '.', '하지만', '이', '고요한', '순간', '속', '에는', '뭔가', '설명', '할', '수', '없는', '따스함이', '있었다', '.', '어쩌면', '그것', '은', '혼자', '가',
'아니라는', '깨달음', '에서', '오는', '안도', '감이었을까', '?']
1-1.대소문자 제거
영어의 경우 단어의 첫부분에 대문자가 오는경우들이 종종 있게 되는데 그러면 아래 예제에서의 Hello 와 hello는 서로 다른 토큰으로 매핑되게될것이다. 이것은 의도와 다르게 토큰화될수있으므로 같은 토큰화를 위해서라면 lower을 통해 소문자로 바꿔준다.
#Cleaning
import tensorflow as tf
# 상수 텐서
text = tf.constant("Hello, hello, Hello")
#소문자화
text = tf.strings.lower(text)
# 단어로 분리
tokens = tf.strings.split(text)
# 결과 출력
# NumPy 배열로 변환해 확인
print(tokens.numpy())
#결과
[b'hello,' b'hello,' b'hello']
1-2.정규표현식
하지만 위의 예제를 보면 "hello," 로 ',' 가 포함된 상태로 토큰화가 진행된것을 볼수있다. 이것을 막기 위해 정규표현식을 사용해서 특수문자들을 제거한다음에 토큰화해보자
#Cleaning
import tensorflow as tf
# 상수 텍스트
text = tf.constant("Hello, hello, Hello!")
# 비문자 제거: 알파벳과 숫자만 남김
text = tf.strings.regex_replace(text, r'[^a-zA-Z0-9 ]', '')
# 소문자화
text = tf.strings.lower(text)
#토큰화
tokens= tf.strings.split(text)
print(tokens.numpy())
#결과
[b'hello' b'hello' b'hello']
1-3.표제어 추출
영어는 복수형을 쓸때 뒤에 s, es 를 붙이는 경우가 많은데 이러한 것들을 하나의 토큰화로 만들기 위해 NLTK의 표제어 추출 도구를 사용한다.
#WordNetLemmatizer
import nltk
from nltk.stem import WordNetLemmatizer
import tensorflow as tf
from nltk.tokenize import word_tokenize
nltk.download('wordnet')
lemmatizer = WordNetLemmatizer()
# 상수 텍스트
text = tf.constant("name,names")
# 소문자화
text = tf.strings.lower(text)
#토큰화
tokens = word_tokenize(text.numpy().decode('utf-8'))
# 알파벳과 숫자만 남김
tokens = [token for token in tokens if token.isalnum()]
#표제어 추출
lemmatized_tokens = [lemmatizer.lemmatize(token) for token in tokens] # decode('utf-8') 필요 없음
# 결과 확인
print(lemmatized_tokens)
# 결과
['name', 'name']
1-4.어간추출
하지만 영어에는 이러한 복수형말고도 과거형 ing형 등등 다양한 단어의 형태들이 존재하는데 이를 하나의 토큰으로 정제하기 위해서 포터 알고리즘을 사용할수있다.
#Stemming
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
import tensorflow as tf
# 포터 알고리즘
stemmer = PorterStemmer()
text = tf.constant("name, naming, named, names")
#정규화
text = tf.strings.lower(text)
tokens = word_tokenize(text.numpy().decode('utf-8'))
tokens = [token for token in tokens if token.isalnum()]
print(tokens)
print([stemmer.stem(word) for word in tokens])
# 결과
['name', 'naming', 'named', 'names']
['name', 'name', 'name', 'name']
1-5.불용어(Stopword)
우리의 글에는 텍스트 데이터에서 의미가 거의 없거나 분석에 큰 영향을 미치지 않는 단어들이 많이 존재한다. 영어에서 a , the , I 등등 자주등장하지만 학습데이터에 필요없는 단어들을 불용어라고 한다. 영어의 불용어리스트들은 nltk에 정리되어있으며 이를 통해 토크에서 불용어를 제거할수있다.
#stopwords
import nltk
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
import tensorflow as tf
nltk.download('stopwords')
#포터 알고리즘
stemmer = PorterStemmer()
text = tf.constant("The internet has revolutionized the way we communicate, learn, and work. It has connected people across the world, breaking down barriers of distance and time. With the rise of social media platforms, individuals can now share their thoughts, ideas, and experiences with a global audience. While the internet has brought countless benefits, it has also introduced new challenges, including privacy concerns and the spread of misinformation. As technology continues to evolve, it is crucial to navigate the digital world responsibly and with awareness.")
text = tf.strings.lower(text)
tokens = word_tokenize(text.numpy().decode('utf-8'))
tokens = [token for token in tokens if token.isalnum()]
tokens = [stemmer.stem(word) for word in tokens]
#불용어
stop_words = set(nltk.corpus.stopwords.words('english'))
result = []
for word in tokens:
if word not in stop_words:
result.append(word)
print(tokens)
print(result)
#결과
['the', 'internet', 'ha', 'revolution', 'the', 'way', 'we', 'commun', 'learn', 'and', 'work', 'it', 'ha', 'connect', 'peopl', 'across', 'the', 'world', 'break', 'down', 'barrier', 'of', 'distanc', 'and', 'time', 'with', 'the', 'rise', 'of', 'social', 'media', 'platform', 'individu', 'can', 'now', 'share', 'their', 'thought', 'idea', 'and', 'experi', 'with', 'a', 'global', 'audienc', 'while', 'the', 'internet', 'ha', 'brought', 'countless', 'benefit', 'it', 'ha', 'also', 'introduc', 'new', 'challeng', 'includ', 'privaci', 'concern', 'and', 'the', 'spread', 'of', 'misinform', 'as', 'technolog', 'continu', 'to', 'evolv', 'it', 'is', 'crucial', 'to', 'navig', 'the', 'digit', 'world', 'respons', 'and', 'with', 'awar']
['internet', 'ha', 'revolution', 'way', 'commun', 'learn', 'work', 'ha', 'connect', 'peopl', 'across', 'world', 'break', 'barrier', 'distanc', 'time', 'rise', 'social', 'media', 'platform', 'individu', 'share', 'thought', 'idea', 'experi', 'global', 'audienc', 'internet', 'ha', 'brought', 'countless', 'benefit', 'ha', 'also', 'introduc', 'new', 'challeng', 'includ', 'privaci', 'concern', 'spread', 'misinform', 'technolog', 'continu', 'evolv', 'crucial', 'navig', 'digit', 'world', 'respons', 'awar']
1-6.한글 불용어
https://www.ranks.nl/stopwords/korean
한글 불용어는 따로 엑셀로 정리하여 제거해주면된다
from konlpy.tag import Okt
import pandas as pd
import os
# 현재 스크립트가 위치한 디렉토리 경로 가져오기
script_dir = os.path.dirname(os.path.realpath(__file__))
# stopwords.xlsx의 절대 경로 생성
file_path = os.path.join(script_dir, 'stopwords.xlsx')
# 엑셀 파일 읽기
df = pd.read_excel(file_path, header=None)
# 첫 번째 열에 있는 데이터를 set으로 변환
stopwords_set = set(df[0].dropna().values)
text="최근 들어 많은 사람들이 취미로 코딩을 배우기 시작했습니다. 특히 온라인 교육 플랫폼과 유튜브 등의 자원을 활용하여 쉽고 빠르게 기초를 배우고 있습니다. 코딩을 배우면 문제 해결 능력도 향상되고, 창의적 사고를 기를 수 있는 장점이 많습니다. 또한, 프로그래밍 언어를 배우면 다양한 분야에서 활용할 수 있어 실용적입니다."
okt = Okt()
tokens = okt.morphs(text)
result = [word for word in tokens if not word in stopwords_set]
# 결과 출력
print(result)
#결과
['최근', '들어', '사람', '취미', '코딩', '배우기', '시작', '했습니다', '.', '특히', '
온라인', '교육', '플랫폼', '유튜브', '자원', '활용', '하여', '쉽고', '빠르게', '기초', '배우고', '있습니다', '.', '코딩', '배우면', '문제', '해결', '능력', '도', '향상', ' 되고', ',', '창의', '적', '사고', '기를', '있는', '장점', '많습니다', '.', ',', '프로 그래밍', '언어', '배우면', '다양한', '분야', '에서', '활용', '있어', '실용', '적', '.']
728x90
'AI' 카테고리의 다른 글
[AI] 원핫 인코딩(One-Hot Encoding) (2) | 2024.12.26 |
---|---|
[AI] 정수 인코딩 (0) | 2024.12.25 |
[AI] from tensorflow.keras.preprocessing.text import Tokenizer 오류 (0) | 2024.12.25 |