NLP/이론 및 정리

[기초정리] 2. 자연어 처리 파이프라인 - 문장 분할(Sentence Segmentation), 단어 토큰화(Word Tokenization)

DongJin Jeong 2021. 1. 1. 19:04

1.문장 분할(Sentence Segmentation)

기계가 이해할 수 있도록 학습시킬 때에는 당연히 글 전체보다 분리된 한 문장, 한 문장을 이해하는 것이 더 수월하다. 문장은 각각 독립적인 의견을 가지고 있기 때문이다. 문장 분할을 가장 쉽게 구현할 수 있는 방법은 구두점(Punctuation Mark)을 활용하는 것이다. 구두점이란 쉼표(,), 마침표(.), 세미콜론(;), 콜론(:) 4가지의 문장 부호를 의미한다.

쉼표(Comma), 마침표(Period), 세미콜론(Semi-colon), 콜론(Colon)

그러나 항상 구두점을 기준으로 나눌 수 있는 상황만 존재하는 것은 아니다.

구현 코드

import nltk

test_text = "All rights reserved. No part of this publication may be reproduced, \
distributed, or transmitted in any form or by any means, including \
photocopying, recording, or other electronic or mechanical methods,\
 without the prior written permission of the publisher, except in the \
 case of brief quotations embodied in critical reviews and certain other \
 noncommercial uses permitted by copyright law. For permission requests, \
 write to the publisher, addressed “Attention: Permissions Coordinator,” \
 at the address below."


def sentence_segmentation(corpus):
    return nltk.tokenize.sent_tokenize(corpus)

print(sentence_segmentation(test_text))

결과

['All rights reserved.', 'No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the  case of brief quotations embodied in critical reviews and certain other  noncommercial uses permitted by copyright law.', 'For permission requests,  write to the publisher, addressed “Attention: Permissions Coordinator,”  at the address below.']

2. 단어 토큰화(Word Tokenization)

토큰(Token)이란 의미를 가지는 문자열을 뜻한다. 상황에 따라 형태소 또는 단어를 의미할 수 있다. 주어진 코퍼스(Corpus)를 토큰으로 나누는 작업을 단어 토큰화(Word Tokenization)라고 한다. 코퍼스(Corpus)란 '말뭉치'라는 뜻이며 NLP 학습에 사용되는 데이터를 의미한다.

구현코드

import nltk

test_text = ['All rights reserved.']

def word_tokenize(sentence_list):
    token_list = list()
    for sentence in sentence_list:
        token_list.append(nltk.tokenize.word_tokenize(sentence))

    return token_list

print(word_tokenize(test_text))

결과

[['All', 'rights', 'reserved', '.']]