Aspect-based sentiment analysis helps us understand feelings about specific parts of something, like a product or service, instead of just the whole thing.
Aspect-based sentiment analysis in NLP
aspect_sentiment_analysis(text, aspects) # text: string with the review or comment # aspects: list of strings with specific parts to check sentiment for # returns: dictionary with aspect as key and sentiment as value
The function takes a text and a list of aspects to find sentiment for each aspect.
Sentiment can be positive, negative, or neutral for each aspect.
aspect_sentiment_analysis("The battery life is great but the screen is dull.", ["battery life", "screen"])
aspect_sentiment_analysis("Food was tasty but the service was slow.", ["food", "service"])
This code looks at each aspect in the review, finds sentences mentioning it, and uses TextBlob to find if the sentiment is positive, negative, or neutral.
from textblob import TextBlob def aspect_sentiment_analysis(text, aspects): results = {} for aspect in aspects: # Find sentences mentioning the aspect sentences = [sent.strip() for sent in text.split('.') if aspect in sent] if not sentences: results[aspect] = 'neutral' continue # Calculate average polarity for these sentences polarity = sum(TextBlob(sent).sentiment.polarity for sent in sentences) / len(sentences) if polarity > 0.1: results[aspect] = 'positive' elif polarity < -0.1: results[aspect] = 'negative' else: results[aspect] = 'neutral' return results # Example usage review = "The battery life is great. The screen is dull. The camera is okay." aspects = ["battery life", "screen", "camera"] result = aspect_sentiment_analysis(review, aspects) print(result)
Aspect-based sentiment analysis breaks down opinions to specific parts, giving clearer insights.
Short sentences mentioning the aspect help get more accurate sentiment.
Thresholds for polarity (like 0.1) can be adjusted based on your needs.
Aspect-based sentiment analysis finds feelings about specific parts, not just the whole.
It helps businesses improve by focusing on what customers like or dislike.
Simple tools like TextBlob can be used to build a basic aspect sentiment analyzer.