Data Analysis & ML/Text Mining

[Text Mining][NLP] 자연어 처리를 위한 NLTK (설치 방법 및 사용 문법)

YSY^ 2020. 9. 9. 17:18

NLTK

  • Natural Language Toolkit(NLTK로 약칭)은 인간 언어 데이터를 더 쉽게 처리하고 사용할 수 있도록 설계된 라이브러리 모음
  • 즉 NLP(Natural Language Processing) (자연어 처리)하기 위한 패키지

NLTK 설치

  • nltk 패키지 설치
    pip 설치conda 설치
  • conda install -y nltk
  • pip install nltk
  • NLTK 추가 패키지 설치
  • import nltk nltk.download() # 설치 GUI 프로그램 실행 nltk.download('패키지명')

NLTK 주요기능

  • 말뭉치(corpus) 제공
    • 말뭉치: 언어 연구를 위해 텍스트를 컴퓨터가 읽을 수 있는 형태로 모아 놓은 언어 자료를 말한다.
    • 예제용 말뭉치 데이터를 제공한다.
  • 텍스트 정규화를 위한 기능 제공
    • 토큰 생성
    • 여러 언어의 Stop word(불용어) 제공
    • 형태소 분석
      • 형태소
        • 의미가 있는 가장 작은 말의 단위
      • 형태소 분석
        • 말뭉치에서 의미있는(분석시 필요한) 형태소들만 추출하는 것
      • 어간추출(Stemming)
      • 원형복원(Lemmatization)
      • 품사부착(POS tagging - Part Of Speech)
  • 분석기능을 제공해 주는 클래스 제공
    • Text
    • FreqDist
import this


text_sample = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""

NLTK 텍스트 정규화 기본 문법

텍스트 토큰화

  • 분석을 위해 문장을 작은 단위로 나누는 작업.
  • 토큰(Token)
    • 나뉜 문자열의 단위를 말한다.
    • 정하기에 따라 문장, 단어일 수도 있고 문자일 수도 있다.
  • Tokenizer
    • 문장을 token으로 나눠주는 함수
    • NLTK 주요 tokenizer
      • sent_tokenize() : 문장단위로 나눠준다.
      • word_tokenize() : 단어단위로 나눠준다.
      • regexp_tokenize() : 토큰의 단위를 정규표현식으로 지정
      • 반환타입 : 토큰하나 하나를 원소로 하는 list
import nltk
nltk.download('punkt')

sentences = nltk.sent_tokenize(text_sample) # 구분자 :"."
print(len(sentences))
print(sentences[0])
sentences

words = nltk.word_tokenize(text_sample) # 구분자: 공백, 구두점도 하나의 토큰 분리.
print(len(words))
words

reg_tokens = nltk.regexp_tokenize(text_sample, '\w+') #토큰의 패턴을 정규표현식으로 지정.  \w 글자,숫자,공백
print(len(reg_tokens))
reg_tokens

Stopword (불용어)

  • 문장내에서는 많이 사용되지만 문장의 전체 맥락(내용/뜻)과는 상관없는 단어들.
    • ex) 조사, 접미사, 접속사, 대명사 등
  • Stopword 단어들을 List로 묶어서 관리한다.
    • nltk가 언어별로 Stop word 제공.
    • 실제 분석대상에 맞는 Stop word 를 만들어서 사용한다.
from nltk.corpus import stopwords
nltk.download('stopwords')


# nltk에서 stop word를 제공하는 언어목록.
stopwords.fileids()
# ['arabic', 'azerbaijani', 'danish', 'dutch', 'english', 'finnish','french', 'german', 'greek', 'hungarian','indonesian', 'italian', 'kazakh', 'nepali', 'norwegian', 'portuguese', 'romanian', 'russian', 'slovene','spanish', 'swedish', 'tajik', 'turkish']

아쉽게도 한국어는 없다.. 한국어는 추후에 KoNLP패키지에서 다루도록 하겠다.

# 영어 불용어
eng_stopwords = stopwords.words('english')
len(eng_stopwords), type(eng_stopwords)
# (179, list)
eng_stopwords[:10]
# ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're"]

tokenize_text() 함수 구현

  • 문장별 토큰화 시키는 함수 구현
  • 쉼표,마침표등 구두점(punctuation)은 공백처리한다.
  • stopword를 제외한다.
import nltk
from nltk.corpus import stopwords

def tokenize_text(text):
    """
    전체 문장들을 받아서 정형데이터 형태로 만들어 반환하는 함수
    문장별로 단어 리스트를 2차원 배열 형태로 반환
    구두점/특수문자, 숫자, 불용어(stop words)들은 모두 제거한다.
    [매개변수]
        text: string - 변환하려는 전체문장
    [반환값] 
        2차원 리스트
    """
    # 받은 문장을 소문자로 변환
    text = text.lower() #string.lower() 소문자로 변환. string.upper() 대문자로 변환

    # 문장단위로 토큰화
    sentence_tokens = nltk.sent_tokenize(text)

    # 불용어 객체 생성
    stop_words = stopwords.words('english')
    stop_words.extend(['although','unless', 'may']) #불용어 객체 추가

    # 반복문을 이용해 문장별로 word 단위 토큰화 실행
    word_token_list = [] # 최종 결과를 저장할 리스트
    for sentence in sentence_tokens:
        word_token_gen = nltk.regexp_tokenize(sentence, '[A-Za-z]+')  # \w: 일반문자, 숫자, 공백
        #불용어 제거
        word_token = [word for word in word_token_gen if word not in stop_words]

        word_token_list.append(word_token)

    return word_token_list

728x90
반응형