고급 자연어 처리를 위한 파이썬 오픈소스 라이브러리이다. 영어의 경우 토큰화를 사용하는 대표적인 도구 중 하나이며 그 외에는 NLTK가 있다. 한국어는 지원하지 않는다.
nlp = spacy.load('en_core_web_sm')
en_core_web_sm
en_core : consist of english language
web : written web text
blog, news, comments
sm : small
1.1 Tokenization
내용 없음
1.2 불용어 (Stopword)
불용어(Stop word)는 분석에 큰 의미가 없는 단어를 지칭한다. 예를 들어 the, a, an, is, I, my 등과 같이 문장을 구성하는 필수 요소지만 문맥적으로 큰 의미가 없는 단어가 이에 속한다.
spacy_stopwords = spacy.lang.en.stop_words.STOP_WORDS
for stop_word in list(spacy_stopwords)[:30]:
print(stop_word)
can
should
herein
whence
more
which
via
therefore
before
from
very
into
beyond
whereafter
‘d
moreover
their
then
's
enough
‘m
and
our
when
done
hereafter
hers
whoever
made
fifteen
spacy에서 지정한 불용어들은 다음과 같다. 내가 보기엔 불용어가 아닌 것 같은 단어도 있는 것 같다.
stopword_text = [token for token in text if not token.is_stop]
print(stopword_text)
spacy로 만들어진 token들은 is_stop 이라는 속성을 가지며 이 값이 True일 경우 불용어에 해당한다. 위 코드는 불용어가 아닌 토큰들을 출력하는 코드
1.3 Lemmatization
표제어 추출이라고 하며, 단어의 어간을 추출하는 작업을 의미한다. 마치 study, studied, studying 에서 study라는 어간을 추출하는 것과 같다.
for token in text[:20]:
print (token, "-", token.lemma_)
The - the
film - film
's - 's
development - development
began - begin
when - when
Marvel - Marvel
Studios - Studios
received - receive
a - a
loan - loan
from - from
Merrill - Merrill
Lynch - Lynch
in - in
April - April
2005 - 2005
. - .
After - after
the - the
1.4 그외 token class의 attributes
print("token \t is_punct \t is_space \t shape_ \t is_stop")
print("="*70)
for token in text[21:31]:
print(token,"\t", token.is_punct, "\t\t",token.is_space,"\t\t", token.shape_, "\t\t",token.is_stop)
is_punct : 문장부호에 해당하는 지
is_space : 공백에 해당하는지
shape : 글자수를 특정 문자의 연속체로 표현하며 각 특정 문자는 다음과 같은 의미가 있다.
x : 소문자
X : 대문자
d : 숫자
, : 기호
빈칸완성 과제 1
def is_token_allowed(token):
# stopword와 punctutation을 제거해주세요.
#if문을 작성해주세요.
##TODO#
if token.is_stop or token.is_punct:
##TODO##
return False
return True
def preprocess_token(token):
#lemmatization을 실행하는 부분입니다.
return token.lemma_.strip().lower()
filtered_tokens = [preprocess_token(token) for token in text if is_token_allowed(token)]
answer=['film', 'development','begin', 'marvel','studios', 'receive','loan', 'merrill','lynch', 'april','2005', 'success','film', 'iron','man', '2008','marvel','announce', 'avengers','release', 'july','2011', 'bring','tony', 'stark','steve', 'rogers','bruce', 'banner','thor', 'marvel','previous', 'film','signing', 'johansson','natasha','romanoff','march','2009','film','push','2012','release','whedon','bring','board','april','2010','rewrote','original','screenplay','zak','penn','production','begin','april','2011','albuquerque','new','mexico','move','cleveland','ohio','august','new','york','city','september','film','2,200','visual','effect','shot']
assert filtered_tokens == answer