[python] NLTK를 사용해 텍스트의 의미 유사도를 계산하는 방법은 무엇인가요?

먼저, 텍스트의 의미 유사도를 계산하기 위해서는 텍스트를 토큰화(tokenization)해야 합니다. 토큰화는 문장을 단어로 나누는 과정을 말합니다. NLTK는 다양한 토큰화 알고리즘을 제공합니다. 예를 들어, 단어 토큰화는 문장을 단어로 나누는 가장 일반적인 방법입니다.

단어를 토큰화한 후에는 단어의 의미를 표현하는 벡터를 생성해야 합니다. 일반적으로 벡터화는 단어를 고정된 길이의 벡터로 변환하는 과정을 말합니다. 이를 위해 자연어 처리 작업에서 널리 사용되는 방법 중 하나는 Word2Vec이며, NLTK에도 Word2Vec 모델을 학습시킬 수 있는 기능이 있습니다.

NLTK에서 Word2Vec 모델을 사용하는 방법은 다음과 같습니다:

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
from gensim.models import Word2Vec

# 불용어(stopwords) 제거
stop_words = set(stopwords.words('english'))

# 텍스트 토큰화
def tokenize_text(text):
    tokens = word_tokenize(text.lower())  # 소문자로 변환
    tokens = [token for token in tokens if token.isalpha()]  # 알파벳 문자만 포함
    tokens = [token for token in tokens if token not in stop_words]  # 불용어 제거
    return tokens

# Word2Vec 모델 학습
def train_word2vec_model(sentences):
    lemmatizer = WordNetLemmatizer()
    preprocessed_sentences = [tokenize_text(sentence) for sentence in sentences]
    lemmatized_sentences = [[lemmatizer.lemmatize(word) for word in sentence] for sentence in preprocessed_sentences]
    model = Word2Vec(sentences=lemmatized_sentences, size=100, window=5, min_count=1)
    return model

# 텍스트 의미 유사도 계산
def compute_similarity(text1, text2, model):
    tokens1 = tokenize_text(text1)
    tokens2 = tokenize_text(text2)
    similarity = model.wv.n_similarity(tokens1, tokens2)
    return similarity

# 예시 문장
sentence1 = "I love coding"
sentence2 = "I enjoy programming"

# Word2Vec 모델 학습
sentences = [sentence1, sentence2]
model = train_word2vec_model(sentences)

# 텍스트 의미 유사도 계산
similarity = compute_similarity(sentence1, sentence2, model)
print("Similarity:", similarity)

위의 예제 코드에서는 NLTK를 사용하여 텍스트를 토큰화하고, 불용어를 제거하며, Word2Vec 모델을 학습하는 방법을 보여줍니다. 이후에는 텍스트의 의미 유사도를 계산하기 위해 compute_similarity 함수를 사용합니다.

참고 자료: