전처리
1.토큰화 -문장 단위 분리/ 단어 단위 분리
2.형태소 분석- 형태소(뜻을 가진 가장 작은 단위)로 분리
3.품사 태깅- 조사/형용사/서술어 등 품사 태깅
4.원형 복원 - 단어의 원형을 복원하여 표준화
어간 추출 -> 품사를 무시하고 규칙에 기반하여 어간을 추출함
표제어 추출 -> 사전 기반 품사정보를 유지하여 표제어 추출
5.불용어 처리 - 분석에 불필요한 단어나 방해되는 단어 제거
pip install nltk
import nltk
nltk.download()
하나 다운로드 창이 뜬다 그거 다운로드 하면됨
import nltk
nltk.download('punkt') #마침표, 구두점 등 다운로드
from nltk.tokenize import word_tokenize
text = 'I love you dangerously more than the air that I breathe'
word_tokens = word_tokenize(text)
print(word_tokens)
텍스트는 내가 좋아하는 댄져러슬리 가사를 넣어봄
토큰화를 하면 이렇게 단어별로 쪼개진다
['I', 'love', 'you', 'dangerously', 'more', 'than', 'the', 'air', 'that', 'I', 'breathe']
TreebandWordTokenizer은 정규표현식에 기반한 토큰화이다
주로 apostrophe가 있는 don't나 they'll 등의 단어들을 'do' ,'n't' , 'they' , ''ll'과 같이 토큰화를 시켜주는 역할을함
import nltk
from nltk.tokenize import TreebankWordTokenizer
text = 'I love you dangerously more than the air that I breathe'
treebankwordtoken = TreebankWordTokenizer().tokenize(text)
print(treebankwordtoken)
품사 태깅
pythonprogramming.net에서 소개하는 품사들이 있다.
https://pythonprogramming.net/natural-language-toolkit-nltk-part-speech-tagging/
앞에서 토큰화된 텍스트(word_tokens)를 받아와서 품사를 태깅한다
from nltk import pos_tag
nltk.download('averaged_perceptron_tagger')
taggedToken = pos_tag(word_tokens)
print(taggedToken)
[('I', 'PRP'), ('love', 'VBP'), ('you', 'PRP'), ('dangerously', 'RB'), ('more', 'RBR'), ('than', 'IN'), ('the', 'DT'), ('air', 'NN'), ('that', 'IN'), ('I', 'PRP'), ('breathe', 'VBP')]
여기서 쓰인 품사는 PRP (인칭대명사), VBP(3인칭을 받지않는 현재동사), RB(부사), RBR(비교급 부사) IN(전치사 또는 종속 접속사), NN(단수명사) 가 쓰였다
다음으로 앞에서 품사를 태깅한 taggedToken 개체명 인식을 한다.
개체명 인식이란 사람, 조직, 지역, 날짜, 숫자 등의 개체 유형을 식별한다.
nltk.download('words')
nltk.download('maxent_ne_chunker')
text = 'Jamie lives in Seoul'
word_tokens = word_tokenize(text)
taggedToken = pos_tag(word_tokens)
from nltk import ne_chunk
neToken = ne_chunk(taggedToken)
print(neToken)
(S (GPE Jamie/NNP) lives/VBZ in/IN (GPE Seoul/NNP))
예를 들어 Jamie lives in Seoul을 예로 들었을 때, Jamie와 Seoul의 개체유형을 인식한다.
어간 추출
어간추출 (stemming)은 품사를 무시하고 규칙에 기반하여 어간을 추출한다.
어간 추출에 대한 규칙은 다음을 참고한다.
https://tartarus.org/martin/PorterStemmer/def.txt
from nltk.stem import PorterStemmer
ps = PorterStemmer()
print("running -> " + ps.stem("running"))
print("beautiful -> " + ps.stem("beautiful"))
print("believes -> " + ps.stem("believes"))
print("using -> " + ps.stem("using"))
print("conversation -> " + ps.stem("conversation"))
print("organization -> " + ps.stem("organization"))
print("studies -> " + ps.stem("studies"))
running -> run
beautiful -> beauti
believes -> believ
using -> use
conversation -> convers
organization -> organ
studies -> studi
표제어 추출
표제어 추출(Lemmatization) 은 어간 추출과 다르게 사전에 기반한 품사 정보를 유지하여 표제어를 추출한다.
from nltk.stem import WordNetLemmatizer
wl = WordNetLemmatizer()
print("running -> " + wl.lemmatize("running"))
print("beautiful -> " + wl.lemmatize("beautiful"))
print("believes -> " + wl.lemmatize("believes"))
print("using -> " + wl.lemmatize("using"))
print("conversation -> " + wl.lemmatize("conversation"))
print("organization -> " + wl.lemmatize("organization"))
print("studies -> " + wl.lemmatize("studies"))
running -> running
beautiful -> beautiful
believes -> belief
using -> using
conversation -> conversation
organization -> organization
studies -> study
불용어 처리
불필요한 요소를 제거하여 효울성을 높인다. 품사제거 / 단어 제거 하는 작업으로 구성되어 있다.
stopPos = ['IN', 'CC', 'UH', 'TO', 'MD', 'DT', 'VBZ','VBP']
# 최빈어 조회. 최빈어를 조회하여 불용어 제거 대상을 선정
from collections import Counter
Counter(taggedToken).most_common()
[(('I', 'PRP'), 2),
(('love', 'VBP'), 1),
(('you', 'PRP'), 1),
(('dangerously', 'RB'), 1),
(('more', 'RBR'), 1),
(('than', 'IN'), 1),
(('the', 'DT'), 1),
(('air', 'NN'), 1),
(('that', 'IN'), 1),
(('breathe', 'VBP'), 1)]
품사태깅+ 토큰화 된 단어들의 빈도수를 조회한 후 불용어 제거 대상을 선정한다.
영화 댓글 분석시 주로 이름이 비슷한, 예를 들어 Tom Hiddleston, 톰, 히들이, 톰 히들스턴 같이 가리키는 대상이 모두 같을때 불용어로 설정한다.
stopWord = ['I','the','that']
word = []
for tag in taggedToken:
if tag[1] not in stopPos:
if tag[0] not in stopWord:
word.append(tag[0])
print(word)
['you', 'dangerously', 'more', 'air']
출처: https://github.com/insightcampus/sesac-nlp/blob/main/ipynb/04%20%E1%84%89%E1%85%B5%E1%86%AF%E1%84%89%E1%85%B3%E1%86%B8%20-%20%E1%84%8C%E1%85%A5%E1%86%AB%E1%84%8E%E1%85%A5%E1%84%85%E1%85%B5%20(Preprocessing).ipynb
'Deep Learning > NLP' 카테고리의 다른 글
05. TF-IDF, N-gram (0) | 2023.03.13 |
---|---|
04. One- Hot Encoding, Similarlity (0) | 2023.03.13 |
02. BeautifulSoup 이용한 네이버 뉴스 데이터 수집 (0) | 2023.03.10 |
01. 통계 기반 자연어 처리 절차 (0) | 2023.03.10 |
KoNLP 설치하기 (0) | 2023.03.10 |