liveBook · Manning

Keyword-based extraction

As explained in Starting Data Analytics with Generative AI and Python

A technique that classifies or extracts text by matching predefined keywords associated with a target category.

Keyword-based extraction classifies or filters text by checking whether predefined terms appear in each record. For example, Portuguese review terms such as “ótimo,” “excelente,” and “recomendo” can flag likely positive reviews. section 5.5.7

import pandas as pd

# Assuming you have already loaded the dataframe and defined the 
is_positive function

# Define a function to determine if a review is positive based on the 
product score
def is_positive_based_on_score(score, threshold=4):
    return score >= threshold

# Apply the function to the 'product_score' column
df['is_positive_based_on_score'] = 
df['product_score'].apply(is_positive_based_on_score)

# Calculate the confusion matrix
TP = sum((df['is_positive'] == True) & (df['is_positive_based_on_score']  
== True))
FP = sum((df['is_positive'] == True) & (df['is_positive_based_on_score']
== False))
TN = sum((df['is_positive'] == False) & (df['is_positive_based_on_score']
== False))
FN = sum((df['is_positive'] == False) & (df['is_positive_based_on_score']
== True))

# Calculate sensitivity (true positive rate) and specificity (true  
negative rate)
sensitivity = TP / (TP + FN)
specificity = TN / (TN + FP)
print(f'Sensitivity: {sensitivity:.2f}')
print(f'Specificity: {specificity:.2f}')

Turns product scores into a second positive-or-negative label, builds a confusion matrix, and calculates sensitivity and specificity for the keyword extraction. section 5.5.7

How Starting Data Analytics with Generative AI and Python covers it

How deep it goes
Demonstrates keyword matching, dataframe labeling, filtering, score comparison, and classification evaluation.
Examples
Uses Portuguese review keywords, an Olist CSV, product scores, and a review-score count plot.
What it assumes
Assumes a dataframe containing review text and product scores, while demonstrating the labeling workflow concretely.
What you can do after
Apply it via pandas to flag reviews, compare extracted labels with score-based labels, and inspect distributions.
How it connects
Connects text classification with product scores, confusion matrices, sensitivity, and specificity.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Starting Data Analytics with Generative AI and Python. The section links point to the parts of the book it draws on.