import re
from typing import List
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
def extract_keywords(text: str, num_keywords: int = 10, max_features: int = 1000) -> List[str]:
"""
Extract top keywords from a given text using TF-IDF.
This function splits the text into sentences to form a small corpus for IDF calculation,
then computes the TF-IDF vector for the entire text and selects the top keywords by score.
Args:
text (str): Input text.
num_keywords (int): Number of top keywords to extract (default: 10).
max_features (int): Maximum number of features for the vectorizer (default: 1000).
Returns:
List[str]: List of top keywords.
Example:
>>> text = "Machine learning is a subset of artificial intelligence. It enables computers to learn from data."
>>> extract_keywords(text, 5)
['machine', 'learning', 'artificial', 'intelligence', 'enables']
"""
if not text or len(text.strip()) == 0:
return []
# Split into sentences for corpus (for IDF)
sentences = re.split(r'[.!?]+', text)
sentences = [s.strip().lower() for s in sentences if len(s.strip()) > 20]
if len(sentences) < 2:
# Fallback: simple word frequency if not enough sentences
words = re.findall(r'\b[a-zA-Z]{3,}\b', text.lower())
from collections import Counter
stop_words = {'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'i', 'it', 'for', 'not', 'on',
'with', 'he', 'as', 'you', 'do', 'at', 'this', 'but', 'his', 'by', 'from', 'they', 'she', 'or',
'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if',
'about', 'who', 'get', 'which', 'go', 'me', 'when', 'make', 'can', 'like', 'time', 'no', 'just',
'him', 'know', 'take', 'people', 'into', 'year', 'your', 'good', 'some', 'could', 'them', 'see',
'other', 'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back',
'after', 'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want',
'because', 'any', 'these', 'give', 'day', 'most', 'us'}
filtered_words = [w for w in words if w not in stop_words]
word_counts = Counter(filtered_words)
return [word for word, _ in word_counts.most_common(num_keywords)]
# Initialize TF-IDF vectorizer
vectorizer = TfidfVectorizer(
stop_words='english',
lowercase=True,
max_features=max_features,
ngram_range=(1, 1),
min_df=1,
max_df=0.8,
token_pattern=r"(?u)\b[a-zA-Z]{3,}\b" # Words with at least 3 letters
)
try:
# Fit on sentences (corpus)
tfidf_matrix = vectorizer.fit_transform(sentences)
# Transform the whole text
whole_text = text.lower()
doc_tfidf = vectorizer.transform([whole_text])
# Get scores
scores = doc_tfidf.toarray()[0]
feature_names = vectorizer.get_feature_names_out()
# Top keywords by score
top_indices = np.argsort(scores)[-num_keywords:][::-1]
keywords = [feature_names[i] for i in top_indices if scores[i] > 0]
return keywords[:num_keywords]
except Exception:
return []
Key Features:
- TF-IDF Computation: Uses scikit-learn's
TfidfVectorizer for robust implementation.
- Single Text Handling: Splits text into sentences to create a mini-corpus for meaningful IDF scores.
- Preprocessing: Lowercasing, stop-word removal (English), min word length (3+ letters).
- Fallback: If insufficient sentences, uses simple term frequency with basic stop words.
- Customizable: Adjust
num_keywords and max_features.
- Dependencies:
scikit-learn, numpy (standard for ML tasks). Install with pip install scikit-learn numpy.
Usage Example:
text = """
Natural language processing (NLP) is a branch of artificial intelligence that focuses on
the interaction between computers and humans through the use of machine language.
NLP enables computers to understand, interpret, and generate human language.
"""
keywords = extract_keywords(text, num_keywords=5)
print(keywords) # Output: ['language', 'nlp', 'natural', 'processing', 'computers']