import pandas as pd
df = pd.read_csv("data/twitter_sentiment_train.csv", encoding = "ISO-8859-1")
smpl_df = df.sample(1000, random_state = 77777)
smpl_df.columns = ["item_id", "sentiment", "text"]
smpl_df.shape
한글의 경우 형태소로 쪼개서 토큰화하는 이유는 한국어에는 조사가 존재하여 영어에서 효과가 검증된 기법을 사용할 수 없다는 점이다.
"Python으로 딥러닝하기 | 자연어 처리 1. 토크나이징"에 나온 사례를 바탕으로 한 문장을 토큰화하는 과정을 비교해보자. 음절은 문자 단위, 어절은 단어 단위 (쉽게 띄어쓰기 단위), 형태소는 의미를 가진 가장 작은 단위로 쪼개는 것이다.
텍스트 품사(POS) 태깅을 위해서 NLTK를 많이 사용했으나, 최근에는 spaCy로 넘어가고 있는 추세다.
아나콘다를 기반으로 작업을 진행하는 경우 다음과 같이 conda install 명령어를 사용해서 spacy를 설치하면 된다.
그리고 나서 영어 사전이 필요하니 python -m spacy 명령어로 영어를 사용할 수 있도록 설치한다.
$ conda install -c conda-forge spacy # conda config --add channels conda-forge$ python -m spacy download en영어 문장을 spaCy를 통해서 Wall Street Journal just published an interesting piece on crypto currencies 영어문장을 형태소분석 작업을 다음과 같이 수행할 수 있고, 이외에도 token.dep_, oken.is_stop 등도 확인할 수 있다.
import spacy
nlp = spacy.load("en_core_web_sm")
print("=="*40)
print("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}".format(
"Text",
"Index",
"Lemma",
"PUNCT",
"Alpha",
"Shape",
"POS",
"TAG"))
print("=="*40)
doc = nlp("Wall Street Journal just published an interesting piece on crypto currencies")
for token in doc:
print("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}".format(
token.text,
token.idx,
token.lemma_,
token.is_punct,
token.is_space,
token.shape_,
token.pos_,
token.tag_
))
stackoverflow, "Applying Spacy Parser to Pandas DataFrame w/ Multiprocessing"를 참조하여 Spacy Parser를 데이터프레임에 멀티프로세싱으로 처리할 수 있다.
tokens = []
lemma = []
pos = []
for doc in nlp.pipe(smpl_df['text'].astype('unicode').values, batch_size=50, n_threads=8):
if doc.is_parsed:
tokens.append([n.text for n in doc])
lemma.append([n.lemma_ for n in doc])
pos.append([n.pos_ for n in doc])
else:
# We want to make sure that the lists of parsed results have the
# same number of entries of the original Dataframe, so add some blanks in case the parse fails
tokens.append(None)
lemma.append(None)
pos.append(None)
smpl_df['text_tokens'] = tokens
smpl_df['text_lemma'] = lemma
smpl_df['text_pos'] = pos
smpl_df.head()