[python] 파이썬 네이처언어 프로세싱 라이브러리를 이용한 기사 요약

이번 포스트에서는 파이썬의 Natural Language Processing (NLP) 라이브러리를 사용하여 기사를 요약하는 방법에 대해 소개하려고 합니다.

라이브러리 소개

파이썬에서는 NLTK (Natural Language Toolkit) 라이브러리를 사용하여 텍스트 데이터를 처리하고 요약할 수 있습니다. NLTK는 토큰화, 어간 추출, 불용어 제거 등 다양한 NLP 기능을 제공합니다.

기사 데이터 다운로드

먼저, 요약할 기사 데이터를 다운로드하거나 웹 크롤링을 통해 획득합니다. 예를 들어, requests 라이브러리를 이용하여 웹 페이지에서 기사 내용을 수집할 수 있습니다.

import requests
from bs4 import BeautifulSoup

url = '기사 URL'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
article = soup.find('기사 내용 태그')

텍스트 전처리

다운로드한 기사 데이터를 전처리하여 NLP 알고리즘에 적용할 수 있는 형태로 변환합니다. 이 단계에는 토큰화, 불용어 제거, 어간 추출 등이 포함될 수 있습니다.

from nltk.tokenize import sent_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer

# 문장 단위로 토큰화
sentences = sent_tokenize(article)

# 불용어 제거
stop_words = set(stopwords.words('english'))
filtered_sentences = [word for word in sentences if not word.lower() in stop_words]

# 어간 추출
stemmer = PorterStemmer()
stemmed_sentences = [stemmer.stem(word) for word in filtered_sentences]

텍스트 요약

요약을 위해 추상적 또는 추출적 방법을 사용할 수 있습니다. 추상적 방법은 원문의 핵심 아이디어를 표현하는 새로운 문장을 생성하는 반면, 추출적 방법은 원문의 문장을 추출하여 요약합니다.

from nltk.probability import FreqDist
import heapq

# 단어 빈도수 계산
word_frequencies = {}
for word in stemmed_sentences:
    if word not in word_frequencies:
        word_frequencies[word] = 1
    else:
        word_frequencies[word] += 1

# 문장 가중치 계산
sentence_scores = {}
for sentence in filtered_sentences:
    for word in sentence:
        if word in word_frequencies:
            if sentence not in sentence_scores:
                sentence_scores[sentence] = word_frequencies[word]
            else:
                sentence_scores[sentence] += word_frequencies[word]

# 상위 문장 추출
summary_sentences = heapq.nlargest(5, sentence_scores, key=sentence_scores.get)
summary = ' '.join(summary_sentences)
print(summary)

마무리

이제 파이썬을 사용하여 기사 요약을 완료했습니다. NLTK를 사용하여 텍스트 데이터를 전처리하고 요약하는 방법을 익히면, 다양한 언어 처리 작업에 적용할 수 있을 것입니다.

이상으로 파이썬을 이용한 기사 요약에 대해 살펴보았습니다. 감사합니다.

참고 자료