Google Cloud Natural Language API client library providing sentiment analysis, entity recognition, text classification, and content moderation capabilities
—
Combines entity recognition with sentiment analysis to determine the sentiment associated with each identified entity. This powerful capability allows you to understand not just what entities are mentioned in text, but how people feel about them. Useful for brand monitoring, reputation management, and understanding public opinion about specific people, places, or topics.
Note: This feature is only available in API versions v1 and v1beta2. It is not included in the simplified v2 API.
Identifies named entities in text and analyzes the sentiment expressed toward each entity.
def analyze_entity_sentiment(
self,
request: Optional[Union[AnalyzeEntitySentimentRequest, dict]] = None,
*,
document: Optional[Document] = None,
encoding_type: Optional[EncodingType] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
) -> AnalyzeEntitySentimentResponse:
"""
Finds entities and analyzes sentiment associated with each entity.
Args:
request: The request object containing document and options
document: Input document for analysis
encoding_type: Text encoding type for offset calculations
retry: Retry configuration for the request
timeout: Request timeout in seconds
metadata: Additional metadata to send with the request
Returns:
AnalyzeEntitySentimentResponse containing entities with sentiment data
"""from google.cloud import language_v1 # Use v1 or v1beta2
# Initialize client (must use v1 or v1beta2)
client = language_v1.LanguageServiceClient()
# Create document
document = language_v1.Document(
content="I love Apple's new iPhone, but I really dislike their customer service. Google's products are amazing!",
type_=language_v1.Document.Type.PLAIN_TEXT
)
# Analyze entity sentiment
response = client.analyze_entity_sentiment(
request={"document": document}
)
# Process entities with sentiment
for entity in response.entities:
print(f"Entity: {entity.name} ({entity.type_.name})")
print(f"Overall sentiment - Score: {entity.sentiment.score:.2f}, Magnitude: {entity.sentiment.magnitude:.2f}")
print(f"Salience: {entity.salience:.2f}")
# Show sentiment for each mention
for mention in entity.mentions:
print(f" Mention: '{mention.text.content}'")
print(f" Sentiment - Score: {mention.sentiment.score:.2f}, Magnitude: {mention.sentiment.magnitude:.2f}")
print()class AnalyzeEntitySentimentRequest:
document: Document
encoding_type: EncodingTypeclass AnalyzeEntitySentimentResponse:
entities: MutableSequence[Entity] # Entities with sentiment information
language: strWhen using entity sentiment analysis, the Entity objects returned include sentiment information:
class Entity:
name: str
type_: Entity.Type
metadata: MutableMapping[str, str]
salience: float
mentions: MutableSequence[EntityMention]
sentiment: Sentiment # Overall sentiment toward this entityEach EntityMention also includes sentiment for that specific mention:
class EntityMention:
text: TextSpan
type_: EntityMention.Type
sentiment: Sentiment # Sentiment for this specific mention
probability: floatdef analyze_brand_sentiment(client, text, target_brands):
"""Analyze sentiment toward specific brands in text."""
document = language_v1.Document(
content=text,
type_=language_v1.Document.Type.PLAIN_TEXT
)
response = client.analyze_entity_sentiment(
request={"document": document}
)
brand_sentiments = {}
for entity in response.entities:
if entity.type_ == language_v1.Entity.Type.ORGANIZATION:
# Check if this entity matches our target brands
for brand in target_brands:
if brand.lower() in entity.name.lower():
brand_sentiments[entity.name] = {
'sentiment_score': entity.sentiment.score,
'sentiment_magnitude': entity.sentiment.magnitude,
'salience': entity.salience,
'mentions': []
}
# Collect mention-level sentiment
for mention in entity.mentions:
brand_sentiments[entity.name]['mentions'].append({
'text': mention.text.content,
'sentiment_score': mention.sentiment.score,
'sentiment_magnitude': mention.sentiment.magnitude
})
return brand_sentiments
# Usage
text = """
I really love Apple's design philosophy, their products are beautiful.
However, Microsoft's customer support is terrible and frustrating.
Google's search engine is incredibly helpful and accurate.
"""
brands = ['Apple', 'Microsoft', 'Google']
sentiment_results = analyze_brand_sentiment(client, text, brands)
for brand, data in sentiment_results.items():
print(f"Brand: {brand}")
print(f"Overall Sentiment: {data['sentiment_score']:.2f} (magnitude: {data['sentiment_magnitude']:.2f})")
print(f"Salience: {data['salience']:.2f}")
print("Mentions:")
for mention in data['mentions']:
print(f" - '{mention['text']}': {mention['sentiment_score']:.2f}")
print()def compare_entity_sentiments(client, text):
"""Compare sentiment across all entities in text."""
document = language_v1.Document(
content=text,
type_=language_v1.Document.Type.PLAIN_TEXT
)
response = client.analyze_entity_sentiment(
request={"document": document}
)
# Sort entities by sentiment score
entities_by_sentiment = sorted(
response.entities,
key=lambda e: e.sentiment.score,
reverse=True
)
print("Entities ranked by sentiment (most positive to most negative):")
for i, entity in enumerate(entities_by_sentiment, 1):
sentiment_label = "Positive" if entity.sentiment.score > 0 else "Negative" if entity.sentiment.score < 0 else "Neutral"
print(f"{i}. {entity.name} ({entity.type_.name})")
print(f" Sentiment: {sentiment_label} (score: {entity.sentiment.score:.2f})")
print(f" Magnitude: {entity.sentiment.magnitude:.2f}")
print(f" Salience: {entity.salience:.2f}")
print()
# Usage
text = """
The new restaurant downtown has amazing food and excellent service.
The chef is incredibly talented. However, the parking situation is awful
and the prices are too expensive for most people.
"""
compare_entity_sentiments(client, text)def analyze_social_media_mentions(client, posts, target_entity):
"""Analyze sentiment toward a specific entity across social media posts."""
results = []
for post in posts:
document = language_v1.Document(
content=post,
type_=language_v1.Document.Type.PLAIN_TEXT
)
response = client.analyze_entity_sentiment(
request={"document": document}
)
# Find mentions of our target entity
for entity in response.entities:
if target_entity.lower() in entity.name.lower():
results.append({
'post': post,
'entity_name': entity.name,
'sentiment_score': entity.sentiment.score,
'sentiment_magnitude': entity.sentiment.magnitude,
'salience': entity.salience
})
return results
# Usage
posts = [
"Just got the new iPhone and it's incredible! Apple really outdid themselves.",
"Apple's customer service was unhelpful and rude. Very disappointed.",
"The Apple Store experience was okay, nothing special but not bad either."
]
results = analyze_social_media_mentions(client, posts, "Apple")
print(f"Sentiment analysis for 'Apple' across {len(posts)} posts:")
for result in results:
print(f"Post: {result['post'][:50]}...")
print(f"Sentiment: {result['sentiment_score']:.2f} (magnitude: {result['sentiment_magnitude']:.2f})")
print(f"Salience: {result['salience']:.2f}")
print()
# Calculate average sentiment
if results:
avg_sentiment = sum(r['sentiment_score'] for r in results) / len(results)
print(f"Average sentiment toward Apple: {avg_sentiment:.2f}")def analyze_product_reviews(client, reviews):
"""Analyze sentiment toward products and features mentioned in reviews."""
all_entity_sentiments = {}
for review in reviews:
document = language_v1.Document(
content=review,
type_=language_v1.Document.Type.PLAIN_TEXT
)
response = client.analyze_entity_sentiment(
request={"document": document}
)
for entity in response.entities:
# Focus on consumer goods and features
if entity.type_ in [language_v1.Entity.Type.CONSUMER_GOOD, language_v1.Entity.Type.OTHER]:
entity_name = entity.name
if entity_name not in all_entity_sentiments:
all_entity_sentiments[entity_name] = {
'sentiments': [],
'total_salience': 0,
'mention_count': 0
}
all_entity_sentiments[entity_name]['sentiments'].append(entity.sentiment.score)
all_entity_sentiments[entity_name]['total_salience'] += entity.salience
all_entity_sentiments[entity_name]['mention_count'] += len(entity.mentions)
# Calculate averages
summary = {}
for entity_name, data in all_entity_sentiments.items():
if data['sentiments']:
summary[entity_name] = {
'average_sentiment': sum(data['sentiments']) / len(data['sentiments']),
'sentiment_range': (min(data['sentiments']), max(data['sentiments'])),
'average_salience': data['total_salience'] / len(data['sentiments']),
'total_mentions': data['mention_count']
}
return summary
# Usage
reviews = [
"The battery life on this phone is excellent, but the camera quality is disappointing.",
"Love the camera features! The battery could be better though.",
"Amazing camera, decent battery, but the screen is fantastic!"
]
summary = analyze_product_reviews(client, reviews)
print("Product Feature Sentiment Summary:")
for feature, data in summary.items():
print(f"{feature}:")
print(f" Average sentiment: {data['average_sentiment']:.2f}")
print(f" Sentiment range: {data['sentiment_range'][0]:.2f} to {data['sentiment_range'][1]:.2f}")
print(f" Average salience: {data['average_salience']:.2f}")
print(f" Total mentions: {data['total_mentions']}")
print()def track_mention_sentiment_changes(client, text):
"""Track how sentiment toward entities changes across mentions."""
document = language_v1.Document(
content=text,
type_=language_v1.Document.Type.PLAIN_TEXT
)
response = client.analyze_entity_sentiment(
request={"document": document}
)
for entity in response.entities:
if len(entity.mentions) > 1: # Only entities with multiple mentions
print(f"Entity: {entity.name}")
print(f"Overall sentiment: {entity.sentiment.score:.2f}")
print("Mention progression:")
for i, mention in enumerate(entity.mentions, 1):
print(f" {i}. '{mention.text.content}' - Sentiment: {mention.sentiment.score:.2f}")
# Calculate sentiment trend
sentiment_scores = [m.sentiment.score for m in entity.mentions]
if len(sentiment_scores) >= 2:
trend = sentiment_scores[-1] - sentiment_scores[0]
trend_label = "improving" if trend > 0.1 else "declining" if trend < -0.1 else "stable"
print(f" Sentiment trend: {trend_label} ({trend:+.2f})")
print()
# Usage
text = """
Initially, I thought the new software was confusing and hard to use.
After trying the software for a week, I found it somewhat useful.
Now I really appreciate the software and think it's quite good.
"""
track_mention_sentiment_changes(client, text)from google.api_core import exceptions
try:
response = client.analyze_entity_sentiment(
request={"document": document},
timeout=20.0
)
except exceptions.InvalidArgument as e:
print(f"Invalid request: {e}")
except exceptions.DeadlineExceeded:
print("Request timed out")
except exceptions.FailedPrecondition as e:
# This might occur if using wrong API version
print(f"API version error: {e}")
print("Note: Entity sentiment analysis requires v1 or v1beta2")
except exceptions.GoogleAPIError as e:
print(f"API error: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-google-cloud-language