본문 바로가기

AI/빅데이터

텍스트 다루기

텍스트 정제하기

# 텍스트 생성
text = ["   Interrobang. By Aishwarya Henriette     ", "Parking And Going. By Karl Gautier", "    Today Is The night. By Jarek Prakash    "]

# 공백문자 제저
strip_whitespace = [string.strip() for string in text]

# 텍스트 확인
print(strip_whitespace)

# 출력
['Interrobang. By Aishwarya Henriette', 'Parking And Going. By Karl Gautier', 'Today Is The night. By Jarek Prakash']

# 마침표 제거
remove_peridos = [string.replace(".", "") for string in text]

# 텍스트 확인
print(remove_peridos)

# 출력
['   Interrobang By Aishwarya Henriette     ', 'Parking And Going By Karl Gautier', '    Today Is The night By Jarek Prakash    ']

# 함수를 이용해 대문자로 변환
def capitalizer(string: str) -> str:
    return string.upper()

# 함수 적용
upper_text = [capitalizer(string) for string in text]

# 텍스트 확인
print(upper_text)

# 출력
['   INTERROBANG. BY AISHWARYA HENRIETTE     ', 'PARKING AND GOING. BY KARL GAUTIER', '    TODAY IS THE NIGHT. BY JAREK PRAKASH    ']

# 텍스트 치환 실행
X_text = [replace_text_with_X(string) for string in text]

# 텍스트 확인
print(X_text)

# 출력
['   XXXXXXXXXXX. XX XXXXXXXXX XXXXXXXXX     ', 'XXXXXXX XXX XXXXX. XX XXXX XXXXXXX', '    XXXXX XX XXX XXXXX. XX XXXXX XXXXXXX    ']

 

HTML 파싱과 정제하기

from bs4 import BeautifulSoup

# HTML 코드 생성
html = """<div class='full_name'><span style='font-weight:bold'>Mesego</span> Azra</dvi>"""

# html 파싱
soup = BeautifulSoup(html, "html.parser")

# "full_name"이름의 클래스를 가진 div를 찾아 텍스트 출력
print(soup.find("div", { "class" : "full_name"}).text)

# 출력
Mesego Azra

구두점 삭제하기

import unicodedata
import sys

# 텍스트 생성
text = ['Hi!!!! I. Love. This. Song.....', '10000% Agree!!!!! #LoveIT', 'Right!?!?!?']

# 구두점 문자로 이루어진 딕셔너리를 생성
punctuation = dict.fromkeys((i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P')))

# 문자열의 구두점을 삭제
test_text = [string.translate(punctuation) for string in text]

# 텍스트 확인
print(test_text)

# 출력
['Hi I Love This Song', '10000 Agree LoveIT', 'Right']

 

텍스트 토큰화하기

import nltk
from nltk.tokenize import word_tokenize

# 구두점 데이터 다운로드
nltk.download('punkt')

# 텍스트 생성
text = "The science of today is the technology of tomorrow"

# 단어를 토큰화 하기
print(word_tokenize(text))

# 출력
['The', 'science', 'of', 'today', 'is', 'the', 'technology', 'of', 'tomorrow']

# 문장으로 토큰화 하기
from nltk.tokenize import sent_tokenize

# 텍스트 생성
text2 = "The science of today is the technology of tomorrow. Tomorrow is today"

# 텍스트 확인
print(sent_tokenize(text2))

# 출력
['The science of today is the technology of tomorrow.', 'Tomorrow is today']

 

불용어 삭제하기

import nltk
from nltk.corpus import stopwords

# 불용어 데이터 다운로드
nltk.download('stopwords')

# 단어 토큰 생성
tokenize_words = ['i', 'am', 'going', 'to', 'the', 'store', 'and', 'park']

# 불용어를 적재
stop_words = stopwords.words('english')

# 불용어를 삭제
stop_words_data = [word for word in tokenize_words if word not in stop_words]

# 출력
print(stop_words_data)

# 결과
['going', 'store', 'park']

 

어간 추출하기

from nltk.stem.porter import PorterStemmer

# 단어 토큰 생성
words = ['i', 'am', 'humbled', 'by', 'this', 'traditional', 'meeting']

# 어간 추출기 생성
porter = PorterStemmer()

# 어간 추출하기
porter_words = [porter.stem(word) for word in words]

# 출력
print(porter_words)

# 결과
['i', 'am', 'humbl', 'by', 'thi', 'tradit', 'meet']

 

품사 태깅하기

import nltk
from nltk import pos_tag
from nltk import word_tokenize

# 태거 다운로드
nltk.download('averaged_perceptron_tagger')

# 텍스트 생성
text = "Chris loved outdoor running"

# 사전 훈련된 품사 태깅 사용
text_tragged = pos_tag(word_tokenize(text))

# 품사 확인
print(text_tragged)

# 출력
[('Chris', 'NNP'), ('loved', 'VBD'), ('outdoor', 'RP'), ('running', 'VBG')]
# 문장을 각 품사에 따라 특성으로 변환하기
import nltk
from nltk import pos_tag
from nltk import word_tokenize
from sklearn.preprocessing import MultiLabelBinarizer


# 텍스트 생성
tweets = ["I am eating a burrito for breakfast", "Political science is an amazing field", "San Francisco is an awesome city"]

# 리스트 생성
tagged_tweets = []

# 각 단어와 텍스트를 태깅
for tweet in tweets:
    tweet_tag = nltk.pos_tag(word_tokenize(tweet))
    tagged_tweets.append([tag for word, tag in tweet_tag])

# 원-핫 인코딩을 사용하여 태그를 특성으로 변환
one_hot_multi = MultiLabelBinarizer()
print(one_hot_multi.fit_transform(tagged_tweets))

# 결과
[[1 1 0 1 0 1 1 1 0]
 [1 0 1 1 0 0 0 0 1]
 [1 0 1 1 1 0 0 0 1]]
 
 # 특성 이름 확인
print(one_hot_multi.classes_)

# 결과
['DT' 'IN' 'JJ' 'NN' 'NNP' 'PRP' 'VBG' 'VBP' 'VBZ']

한글 태깅하기

from konlpy.tag import Okt
okt = Okt()

# 텍스트 생성
text = "태양계는 지금으로부터 약 46억 년 전, 거대한 분자 구름의 일부분이 중력 붕괴를 일으키면서 형성되었다."

# 출력
print(okt.pos(text))

# 결과
[('태양계', 'Noun'), ('는', 'Josa'), ('지금', 'Noun'), ('으로부터', 'Josa'), ('약', 'Noun'), ('46억', 'Number'), ('년', 'Noun'), ('전', 'Noun'), (',', 'Punctuation'), ('거대한', 'Adjective'), ('분자', 'Noun'), ('구름', 'Noun'), ('의', 'Josa'), ('일부분', 'Noun'), ('이', 'Josa'), ('중력', 'Noun'), ('붕괴', 'Noun'), ('를', 'Josa'), ('일으키면서', 'Verb'), ('형성', 'Noun'), ('되었다', 'Verb'), ('.', 'Punctuation')]

# 형태소 추출하기
print(okt.morphs(text))

# 결과
['태양계', '는', '지금', '으로부터', '약', '46억', '년', '전', ',', '거대한', '분자', '구름', '의', '일부분', '이', '중력', '붕괴', '를', '일으키면서', '형성', '되었다', '.']

# 명사 추출하기
print(okt.nouns(text))

# 결과
['태양계', '지금', '약', '년', '전', '분자', '구름', '일부분', '중력', '붕괴', '형성']

 

텍스트를 BoW로 인코딩하기

- Bow(Bag of Words)는 텍스트 데이터에 있는 고유한 단어마다 하나의 특성을 생서ㅏㅇ 이 특성은 각 단어가 샘플에 등장한 횟수를 담고있음.

import numpy as np
from sklearn.feature_extraction.text import CountVectorizer

# 텍스트 생성
text = np.array(['I love Brazil. Brazil!', 'Sweden is best', 'Germany beats both'])

# BoW 특성 행렬 생성
count = CountVectorizer()
bag_of_words = count.fit_transform(text)

# 특성 행렬 확인
print(bag_of_words)


# 결과
  (0, 6)	1
  (0, 3)	2
  (1, 7)	1
  (1, 5)	1
  (1, 1)	1
  (2, 4)	1
  (2, 0)	1
  (2, 2)	1
  
  # 단어 카운트 행렬 확인
print(bag_of_words.toarray())

# 결과
[[0 0 0 2 0 0 1 0]
 [0 1 0 0 0 1 0 1]
 [1 0 1 0 1 0 0 0]]
 
 # 특성 이름 확인
print(count.get_feature_names())

# 결과
['beats', 'best', 'both', 'brazil', 'germany', 'is', 'love', 'sweden']

 

# 단어 중요도에 가중치 부여하기

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

# 텍스트 생성
text = np.array(['I love Brazil. Brazil!', 'Sweden is best', 'Germany beats both'])

# tf-idf 특성 행렬 생성
tfidf = TfidfVectorizer()
feature_matrix = tfidf.fit_transform(text)

# tf-idf 특성 행렬 확인
print(feature_matrix)

# 결과
  (0, 3)	0.8944271909999159
  (0, 6)	0.4472135954999579
  (1, 1)	0.5773502691896257
  (1, 5)	0.5773502691896257
  (1, 7)	0.5773502691896257
  (2, 2)	0.5773502691896257
  (2, 0)	0.5773502691896257
  (2, 4)	0.5773502691896257
  
  # tf-idf 특성 행렬을 밀집 배열로 확인
print(feature_matrix.toarray())

# 결과
[[0.         0.         0.         0.89442719 0.         0.
  0.4472136  0.        ]
 [0.         0.57735027 0.         0.         0.         0.57735027
  0.         0.57735027]
 [0.57735027 0.         0.57735027 0.         0.57735027 0.
  0.         0.        ]]
  

'AI > 빅데이터' 카테고리의 다른 글

범주형 데이터 다루기  (0) 2021.06.23
수치형 데이터 다루기  (0) 2021.06.22
3.하둡-YARN  (0) 2021.02.18
3.하둡-맵리듀스  (0) 2021.02.18
3.하둡-2  (0) 2021.02.18