Implementing keyword extraction
The user is asking for a Python function to extract keywords from text using TF-IDF, likely wanting example code and maybe some explanation. I think using scikit-learn’s TfidfVectorizer is a solid choice, and I’ll handle both single and multiple documents. I’ll create a function called extract_keywords(text, n=10) and provide a code snippet with a clear explanation. Since the environment doesn’t allow package installation, I’ll work under the assumption that scikit-learn is available. I'll keep it simple but concise!Creating a keyword extraction function
I’m thinking about how to implement a keyword extraction function using scikit-learn’s TfidfVectorizer. I should start with the imports and define a function like extract_keywords(docs, doc_index=0, top_n=10). However, if the user provides just one document, I could simplify it to extract_keywords(text, top_n=10), focusing on that single input.
To enhance usability, I'll also add options for handling n-grams and customizing stop words. Along with the code, I’ll provide a usage example and mention how to install scikit-learn, keeping the explanation brief. Here’s a simple TF‑IDF-based keyword extractor in Python using scikit‑learn.
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
def extract_keywords(text, top_n=10, ngram_range=(1, 1)):
"""
Extract top-N keywords from a single text using TF-IDF.
Parameters
----------
text : str
Input text document.
top_n : int
Number of keywords to return.
ngram_range : tuple (min_n, max_n)
The lower and upper boundary of the n-grams to be extracted.
Returns
-------
List[Tuple[str, float]]
List of (keyword, score) sorted by score descending.
"""
# Create TF-IDF vectorizer
vectorizer = TfidfVectorizer(
stop_words='english', # remove English stopwords
ngram_range=ngram_range, # unigrams, bigrams, etc.
max_df=0.85, # ignore very common terms
min_df=1 # keep terms that appear at least once
)
# Fit and transform the text
tfidf_matrix = vectorizer.fit_transform([text]) # shape: (1, vocab_size)
feature_names = np.array(vectorizer.get_feature_names_out())
tfidf_scores = tfidf_matrix.toarray()[0]
# Get indices of top-N highest scores
top_n_idx = np.argsort(tfidf_scores)[::-1][:top_n]
keywords = [(feature_names[i], float(tfidf_scores[i])) for i in top_n_idx]
return keywords
Example usage:
text = """
Machine learning is a field of artificial intelligence that uses statistical
techniques to give computer systems the ability to learn from data.
"""
keywords = extract_keywords(text, top_n=5, ngram_range=(1, 2))
for kw, score in keywords:
print(f"{kw}: {score:.4f}")
If you don’t have scikit‑learn installed:
pip install scikit-learn