텍스트 전처리
KeyWord
토큰화 , 불용어제거
자연어처리 관련 용어
- 코퍼스(Corpus, 말뭉치)란 특정한 목적을 가지고 수집한 텍스트 데이터를 말합니다.
- 문서(Document)란 문장(Sentence)들의 집합입니다
- 문장(Sentence)이란 여러개의 토큰(단어, 형태소 등)으로 구성된 문자열 입니다. 마침표, 느낌표 같은 기호로 주로 구분됩니다.
- 어휘집합(Vocabulary)는 코퍼스에 있는 모든 문서, 문장을 토큰화한 후 중복을 제거한 토큰의 집합을 말합니다.
NLP pipeline

1. 통계기반, 말뭉치 이용
#말뭉치 전처리
text = "Hello world! nice to meet you! python is nice language!"
#문자열을 소문자로 통일하기
text = text.lower()
# !를 .으로 변경
text = text.replace('!', ' , ')
print(text)
-> 'hello world . nice to meet you . python is nice language .'
#split words
word = txet.split(' ')

텍스트 토큰화 (Tokenization)
토큰 : 쉽게 말해 의미를 가지는 최소한의 문자덩어리
토큰화를 하기 위해 크게 3가지 과정을 거친다
1. .split()를 이용하여 단어별로 쪼개주기!
2. 문자를 모두 대문자 or 소문자로 통일해주기 ! (복잡도를 줄이고 읽기 쉽게 하기 위함)
3. 특수문자 및 부호, 공백 제거하기! ( 분석에 관련 없는 정보 제거 )
1. 단어별로 쪼개주기 (순화해서 표현하면.. iterable 데이터 구조에 저장하기!)
words = "Constructor, Leadership, refer, Yeah, way to go, buddy!;"
words.split(" ")
.split()를 사용해 공백으로 문장을 나누면 단어가 iterable 단위가 되어 리스트에 저장할 수 있다 !!

2. 대소문자 정제하기
.upper() -> 대문자
.lower() -> 소문자
#lambda함수를 이용해서 해당컬럼 소문자로 맞춰주기
df['컬럼명'] = df['컬럼명'].apply(lambda x: x.lower())
3. 영문과 숫자만 남기고 제거하기 !! 특히 \n이런 것들
# 정규식 라이브러리
import re
# 정규식
# []: [] 사이 문자를 매치, ^: not
regex = r"[^a-zA-Z0-9 ]"
# 정규식을 적용할 스트링
test_str = ("(Natural Language Processing) is easy!, DS!\n")
# 치환할 문자
subst = ""
result = re.sub(regex, subst, test_str)
불용어 (Stop Words)처리
불용어 처리를 하는 방법은 다양하다
내가 주로 사용하는 방법은 불용어 사전을 txt파일로 구축하여 적용시켜주는 방법을 사용하는데.
오늘 얘기할 방법은 Spacy모델에서 기본 불용어를 가져오는것.
# spacy.io
import spacy
from spacy.tokenizer import Tokenizer
# Load general-purpose pretrained models to predict named entities, part-of-speech tags and syntactic dependencies
## https://spacy.io/models
## python -m spacy download en_core_web_lg
nlp = spacy.load("en_core_web_sm")
# Tokenizer 생성
tokenizer = Tokenizer(nlp.vocab)
print(nlp.Defaults.stop_words)

tokens = []
for doc in tokenizer.pipe(df['컬럼명']):
doc_tokens = []
#불용어를 제외한 나머지 token 리스트 저장
for token in doc:
if token.text.lower() not in STOP_WORDS:
doc_tokens.append(token.text.lower())
tokens.append(doc_tokens)
#새컬럼
df['tokens'] = tokens
txt파일 이용해서 불용어처리하기 .!
def define_stopwords(path):
SW = set()
#집합형태로 만들어줘야 중복을 제외하고 출력해줌
#불용어들을 추가할려면 SW.add()이렇게 넣어주면 됨
with open(path, encoding = 'cp949') as f:
for word in f:
SW.add(word)
return SW
# 함수지정
# 불용어사전을 만들어주는 함수(for문을 통해 set형태로 하나씩 넣어줌)
#SW = define_stopwords('gdrive/My Drive/pytest/stopwords-ko.txt')
# 지정한 함수를 활용하여 구글드라이브에 불용어를 넣어놓은 텍스트파일을 불러옴
다음은 표제어추출(lemmatization)과 어간추출(Stemming)을 알아보겠따!!
텍스트 전처리
KeyWord
토큰화 , 불용어제거
자연어처리 관련 용어
- 코퍼스(Corpus, 말뭉치)란 특정한 목적을 가지고 수집한 텍스트 데이터를 말합니다.
- 문서(Document)란 문장(Sentence)들의 집합입니다
- 문장(Sentence)이란 여러개의 토큰(단어, 형태소 등)으로 구성된 문자열 입니다. 마침표, 느낌표 같은 기호로 주로 구분됩니다.
- 어휘집합(Vocabulary)는 코퍼스에 있는 모든 문서, 문장을 토큰화한 후 중복을 제거한 토큰의 집합을 말합니다.
NLP pipeline

1. 통계기반, 말뭉치 이용
#말뭉치 전처리
text = "Hello world! nice to meet you! python is nice language!"
#문자열을 소문자로 통일하기
text = text.lower()
# !를 .으로 변경
text = text.replace('!', ' , ')
print(text)
-> 'hello world . nice to meet you . python is nice language .'
#split words
word = txet.split(' ')

텍스트 토큰화 (Tokenization)
토큰 : 쉽게 말해 의미를 가지는 최소한의 문자덩어리
토큰화를 하기 위해 크게 3가지 과정을 거친다
1. .split()를 이용하여 단어별로 쪼개주기!
2. 문자를 모두 대문자 or 소문자로 통일해주기 ! (복잡도를 줄이고 읽기 쉽게 하기 위함)
3. 특수문자 및 부호, 공백 제거하기! ( 분석에 관련 없는 정보 제거 )
1. 단어별로 쪼개주기 (순화해서 표현하면.. iterable 데이터 구조에 저장하기!)
words = "Constructor, Leadership, refer, Yeah, way to go, buddy!;"
words.split(" ")
.split()를 사용해 공백으로 문장을 나누면 단어가 iterable 단위가 되어 리스트에 저장할 수 있다 !!

2. 대소문자 정제하기
.upper() -> 대문자
.lower() -> 소문자
#lambda함수를 이용해서 해당컬럼 소문자로 맞춰주기
df['컬럼명'] = df['컬럼명'].apply(lambda x: x.lower())
3. 영문과 숫자만 남기고 제거하기 !! 특히 \n이런 것들
# 정규식 라이브러리
import re
# 정규식
# []: [] 사이 문자를 매치, ^: not
regex = r"[^a-zA-Z0-9 ]"
# 정규식을 적용할 스트링
test_str = ("(Natural Language Processing) is easy!, DS!\n")
# 치환할 문자
subst = ""
result = re.sub(regex, subst, test_str)
불용어 (Stop Words)처리
불용어 처리를 하는 방법은 다양하다
내가 주로 사용하는 방법은 불용어 사전을 txt파일로 구축하여 적용시켜주는 방법을 사용하는데.
오늘 얘기할 방법은 Spacy모델에서 기본 불용어를 가져오는것.
# spacy.io
import spacy
from spacy.tokenizer import Tokenizer
# Load general-purpose pretrained models to predict named entities, part-of-speech tags and syntactic dependencies
## https://spacy.io/models
## python -m spacy download en_core_web_lg
nlp = spacy.load("en_core_web_sm")
# Tokenizer 생성
tokenizer = Tokenizer(nlp.vocab)
print(nlp.Defaults.stop_words)

tokens = []
for doc in tokenizer.pipe(df['컬럼명']):
doc_tokens = []
#불용어를 제외한 나머지 token 리스트 저장
for token in doc:
if token.text.lower() not in STOP_WORDS:
doc_tokens.append(token.text.lower())
tokens.append(doc_tokens)
#새컬럼
df['tokens'] = tokens
txt파일 이용해서 불용어처리하기 .!
def define_stopwords(path):
SW = set()
#집합형태로 만들어줘야 중복을 제외하고 출력해줌
#불용어들을 추가할려면 SW.add()이렇게 넣어주면 됨
with open(path, encoding = 'cp949') as f:
for word in f:
SW.add(word)
return SW
# 함수지정
# 불용어사전을 만들어주는 함수(for문을 통해 set형태로 하나씩 넣어줌)
#SW = define_stopwords('gdrive/My Drive/pytest/stopwords-ko.txt')
# 지정한 함수를 활용하여 구글드라이브에 불용어를 넣어놓은 텍스트파일을 불러옴
다음은 표제어추출(lemmatization)과 어간추출(Stemming)을 알아보겠따!!