[파이썬] 텍스트 분석을 위한 키워드 추출 기법

텍스트 분석은 자연어 처리의 중요한 분야 중 하나입니다. 텍스트를 이해하고 분류하며, 텍스트로부터 유용한 정보를 추출하는 것은 다양한 분야에서 매우 유용합니다. 그 중에서도 키워드 추출은 텍스트에서 가장 중요한 단어나 구를 식별하고 결정하는 데 사용되는 기술입니다.

키워드 추출은 다양한 응용 분야에서 활용될 수 있습니다. 예를 들어, 문서의 주제를 파악하기 위해 키워드를 추출하거나, 문서의 중요한 토픽을 파악하기 위해 키워드를 사용할 수 있습니다. 이러한 키워드 추출은 기계 학습, 정보 검색, 자동 요약 등의 분야에서 자주 사용됩니다.

키워드 추출 기법

텍스트에서 키워드를 추출하는 다양한 기법들이 있습니다. 이 중에서 우리는 TF-IDFTextRank라는 두 가지 기법에 대해 알아볼 것입니다.

TF-IDF (Term Frequency-Inverse Document Frequency)

TF-IDF는 특정 단어의 중요도를 계산하는 데 사용되는 통계적 척도입니다. 이 방법은 단어의 출현 빈도인 Term Frequency (TF)와 단어의 문서 내 전체 단어 수에 대한 역수인 Inverse Document Frequency (IDF)를 곱하여 계산됩니다.

from sklearn.feature_extraction.text import TfidfVectorizer

# 문서 집합을 생성합니다
documents = ["This is a sample document.",
             "Another document is a document document.",
             "And another document is here."]

# TF-IDF 벡터화를 수행합니다
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)

# 키워드를 추출합니다
keywords = vectorizer.get_feature_names()
print(keywords)

TextRank

TextRankPageRank 알고리즘을 활용하여 텍스트의 단어와 문장의 중요성을 결정하는 데 사용됩니다. 이 알고리즘은 단어와 문장을 그래프로 표현하고, 각 노드의 중요도를 계산하여 최종적으로 중요한 단어와 문장을 추출합니다.

import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from collections import defaultdict

# 텍스트를 전처리합니다 (문장 토큰화, 단어 토큰화, 불용어 제거, 어간 추출)
def preprocess_text(text):
    sentences = sent_tokenize(text)
    words = []
    for sentence in sentences:
        tokens = word_tokenize(sentence.lower())
        filtered_tokens = [word for word in tokens if word not in stopwords.words('english')]
        stemmed_tokens = [PorterStemmer().stem(word) for word in filtered_tokens]
        words.extend(stemmed_tokens)
    return words

# 문서의 그래프를 생성합니다
def create_graph(documents):
    graph = defaultdict(list)
    for doc in documents:
        words = preprocess_text(doc)
        for i in range(len(words)-1):
            graph[words[i]].append(words[i+1])
    return graph

# TextRank 알고리즘을 수행하여 키워드를 추출합니다
def extract_keywords(text, n_keywords=5):
    graph = create_graph([text])
    scores = nltk.centroid.TextRank(graph).scores
    keywords = [word for word, score in sorted(scores.items(), key=lambda x: x[1], reverse=True)[:n_keywords]]
    return keywords

# 키워드를 추출합니다
keywords = extract_keywords("This is a sample document. Another document is a document document. And another document is here.")
print(keywords)

결론

텍스트 분석을 위한 키워드 추출 기법에는 여러 가지 방법들이 있습니다. 이 글에서는 TF-IDF와 TextRank 두 가지 기법에 대해 알아보았습니다. 이러한 키워드 추출 기법들은 다양한 응용 분야에서 유용하게 활용될 수 있습니다.