0
# Entity Sentiment Analysis (v1/v1beta2 only)
1
2
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.
3
4
**Note**: This feature is only available in API versions v1 and v1beta2. It is not included in the simplified v2 API.
5
6
## Capabilities
7
8
### Analyze Entity Sentiment
9
10
Identifies named entities in text and analyzes the sentiment expressed toward each entity.
11
12
```python { .api }
13
def analyze_entity_sentiment(
14
self,
15
request: Optional[Union[AnalyzeEntitySentimentRequest, dict]] = None,
16
*,
17
document: Optional[Document] = None,
18
encoding_type: Optional[EncodingType] = None,
19
retry: OptionalRetry = gapic_v1.method.DEFAULT,
20
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
21
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
22
) -> AnalyzeEntitySentimentResponse:
23
"""
24
Finds entities and analyzes sentiment associated with each entity.
25
26
Args:
27
request: The request object containing document and options
28
document: Input document for analysis
29
encoding_type: Text encoding type for offset calculations
30
retry: Retry configuration for the request
31
timeout: Request timeout in seconds
32
metadata: Additional metadata to send with the request
33
34
Returns:
35
AnalyzeEntitySentimentResponse containing entities with sentiment data
36
"""
37
```
38
39
#### Usage Example
40
41
```python
42
from google.cloud import language_v1 # Use v1 or v1beta2
43
44
# Initialize client (must use v1 or v1beta2)
45
client = language_v1.LanguageServiceClient()
46
47
# Create document
48
document = language_v1.Document(
49
content="I love Apple's new iPhone, but I really dislike their customer service. Google's products are amazing!",
50
type_=language_v1.Document.Type.PLAIN_TEXT
51
)
52
53
# Analyze entity sentiment
54
response = client.analyze_entity_sentiment(
55
request={"document": document}
56
)
57
58
# Process entities with sentiment
59
for entity in response.entities:
60
print(f"Entity: {entity.name} ({entity.type_.name})")
61
print(f"Overall sentiment - Score: {entity.sentiment.score:.2f}, Magnitude: {entity.sentiment.magnitude:.2f}")
62
print(f"Salience: {entity.salience:.2f}")
63
64
# Show sentiment for each mention
65
for mention in entity.mentions:
66
print(f" Mention: '{mention.text.content}'")
67
print(f" Sentiment - Score: {mention.sentiment.score:.2f}, Magnitude: {mention.sentiment.magnitude:.2f}")
68
print()
69
```
70
71
## Request and Response Types
72
73
### AnalyzeEntitySentimentRequest
74
75
```python { .api }
76
class AnalyzeEntitySentimentRequest:
77
document: Document
78
encoding_type: EncodingType
79
```
80
81
### AnalyzeEntitySentimentResponse
82
83
```python { .api }
84
class AnalyzeEntitySentimentResponse:
85
entities: MutableSequence[Entity] # Entities with sentiment information
86
language: str
87
```
88
89
## Entity with Sentiment
90
91
When using entity sentiment analysis, the `Entity` objects returned include sentiment information:
92
93
```python { .api }
94
class Entity:
95
name: str
96
type_: Entity.Type
97
metadata: MutableMapping[str, str]
98
salience: float
99
mentions: MutableSequence[EntityMention]
100
sentiment: Sentiment # Overall sentiment toward this entity
101
```
102
103
Each `EntityMention` also includes sentiment for that specific mention:
104
105
```python { .api }
106
class EntityMention:
107
text: TextSpan
108
type_: EntityMention.Type
109
sentiment: Sentiment # Sentiment for this specific mention
110
probability: float
111
```
112
113
## Advanced Usage
114
115
### Brand Sentiment Monitoring
116
117
```python
118
def analyze_brand_sentiment(client, text, target_brands):
119
"""Analyze sentiment toward specific brands in text."""
120
document = language_v1.Document(
121
content=text,
122
type_=language_v1.Document.Type.PLAIN_TEXT
123
)
124
125
response = client.analyze_entity_sentiment(
126
request={"document": document}
127
)
128
129
brand_sentiments = {}
130
131
for entity in response.entities:
132
if entity.type_ == language_v1.Entity.Type.ORGANIZATION:
133
# Check if this entity matches our target brands
134
for brand in target_brands:
135
if brand.lower() in entity.name.lower():
136
brand_sentiments[entity.name] = {
137
'sentiment_score': entity.sentiment.score,
138
'sentiment_magnitude': entity.sentiment.magnitude,
139
'salience': entity.salience,
140
'mentions': []
141
}
142
143
# Collect mention-level sentiment
144
for mention in entity.mentions:
145
brand_sentiments[entity.name]['mentions'].append({
146
'text': mention.text.content,
147
'sentiment_score': mention.sentiment.score,
148
'sentiment_magnitude': mention.sentiment.magnitude
149
})
150
151
return brand_sentiments
152
153
# Usage
154
text = """
155
I really love Apple's design philosophy, their products are beautiful.
156
However, Microsoft's customer support is terrible and frustrating.
157
Google's search engine is incredibly helpful and accurate.
158
"""
159
160
brands = ['Apple', 'Microsoft', 'Google']
161
sentiment_results = analyze_brand_sentiment(client, text, brands)
162
163
for brand, data in sentiment_results.items():
164
print(f"Brand: {brand}")
165
print(f"Overall Sentiment: {data['sentiment_score']:.2f} (magnitude: {data['sentiment_magnitude']:.2f})")
166
print(f"Salience: {data['salience']:.2f}")
167
print("Mentions:")
168
for mention in data['mentions']:
169
print(f" - '{mention['text']}': {mention['sentiment_score']:.2f}")
170
print()
171
```
172
173
### Comparative Sentiment Analysis
174
175
```python
176
def compare_entity_sentiments(client, text):
177
"""Compare sentiment across all entities in text."""
178
document = language_v1.Document(
179
content=text,
180
type_=language_v1.Document.Type.PLAIN_TEXT
181
)
182
183
response = client.analyze_entity_sentiment(
184
request={"document": document}
185
)
186
187
# Sort entities by sentiment score
188
entities_by_sentiment = sorted(
189
response.entities,
190
key=lambda e: e.sentiment.score,
191
reverse=True
192
)
193
194
print("Entities ranked by sentiment (most positive to most negative):")
195
for i, entity in enumerate(entities_by_sentiment, 1):
196
sentiment_label = "Positive" if entity.sentiment.score > 0 else "Negative" if entity.sentiment.score < 0 else "Neutral"
197
print(f"{i}. {entity.name} ({entity.type_.name})")
198
print(f" Sentiment: {sentiment_label} (score: {entity.sentiment.score:.2f})")
199
print(f" Magnitude: {entity.sentiment.magnitude:.2f}")
200
print(f" Salience: {entity.salience:.2f}")
201
print()
202
203
# Usage
204
text = """
205
The new restaurant downtown has amazing food and excellent service.
206
The chef is incredibly talented. However, the parking situation is awful
207
and the prices are too expensive for most people.
208
"""
209
210
compare_entity_sentiments(client, text)
211
```
212
213
### Social Media Sentiment Analysis
214
215
```python
216
def analyze_social_media_mentions(client, posts, target_entity):
217
"""Analyze sentiment toward a specific entity across social media posts."""
218
results = []
219
220
for post in posts:
221
document = language_v1.Document(
222
content=post,
223
type_=language_v1.Document.Type.PLAIN_TEXT
224
)
225
226
response = client.analyze_entity_sentiment(
227
request={"document": document}
228
)
229
230
# Find mentions of our target entity
231
for entity in response.entities:
232
if target_entity.lower() in entity.name.lower():
233
results.append({
234
'post': post,
235
'entity_name': entity.name,
236
'sentiment_score': entity.sentiment.score,
237
'sentiment_magnitude': entity.sentiment.magnitude,
238
'salience': entity.salience
239
})
240
241
return results
242
243
# Usage
244
posts = [
245
"Just got the new iPhone and it's incredible! Apple really outdid themselves.",
246
"Apple's customer service was unhelpful and rude. Very disappointed.",
247
"The Apple Store experience was okay, nothing special but not bad either."
248
]
249
250
results = analyze_social_media_mentions(client, posts, "Apple")
251
252
print(f"Sentiment analysis for 'Apple' across {len(posts)} posts:")
253
for result in results:
254
print(f"Post: {result['post'][:50]}...")
255
print(f"Sentiment: {result['sentiment_score']:.2f} (magnitude: {result['sentiment_magnitude']:.2f})")
256
print(f"Salience: {result['salience']:.2f}")
257
print()
258
259
# Calculate average sentiment
260
if results:
261
avg_sentiment = sum(r['sentiment_score'] for r in results) / len(results)
262
print(f"Average sentiment toward Apple: {avg_sentiment:.2f}")
263
```
264
265
### Product Review Analysis
266
267
```python
268
def analyze_product_reviews(client, reviews):
269
"""Analyze sentiment toward products and features mentioned in reviews."""
270
all_entity_sentiments = {}
271
272
for review in reviews:
273
document = language_v1.Document(
274
content=review,
275
type_=language_v1.Document.Type.PLAIN_TEXT
276
)
277
278
response = client.analyze_entity_sentiment(
279
request={"document": document}
280
)
281
282
for entity in response.entities:
283
# Focus on consumer goods and features
284
if entity.type_ in [language_v1.Entity.Type.CONSUMER_GOOD, language_v1.Entity.Type.OTHER]:
285
entity_name = entity.name
286
287
if entity_name not in all_entity_sentiments:
288
all_entity_sentiments[entity_name] = {
289
'sentiments': [],
290
'total_salience': 0,
291
'mention_count': 0
292
}
293
294
all_entity_sentiments[entity_name]['sentiments'].append(entity.sentiment.score)
295
all_entity_sentiments[entity_name]['total_salience'] += entity.salience
296
all_entity_sentiments[entity_name]['mention_count'] += len(entity.mentions)
297
298
# Calculate averages
299
summary = {}
300
for entity_name, data in all_entity_sentiments.items():
301
if data['sentiments']:
302
summary[entity_name] = {
303
'average_sentiment': sum(data['sentiments']) / len(data['sentiments']),
304
'sentiment_range': (min(data['sentiments']), max(data['sentiments'])),
305
'average_salience': data['total_salience'] / len(data['sentiments']),
306
'total_mentions': data['mention_count']
307
}
308
309
return summary
310
311
# Usage
312
reviews = [
313
"The battery life on this phone is excellent, but the camera quality is disappointing.",
314
"Love the camera features! The battery could be better though.",
315
"Amazing camera, decent battery, but the screen is fantastic!"
316
]
317
318
summary = analyze_product_reviews(client, reviews)
319
320
print("Product Feature Sentiment Summary:")
321
for feature, data in summary.items():
322
print(f"{feature}:")
323
print(f" Average sentiment: {data['average_sentiment']:.2f}")
324
print(f" Sentiment range: {data['sentiment_range'][0]:.2f} to {data['sentiment_range'][1]:.2f}")
325
print(f" Average salience: {data['average_salience']:.2f}")
326
print(f" Total mentions: {data['total_mentions']}")
327
print()
328
```
329
330
### Mention-Level Sentiment Tracking
331
332
```python
333
def track_mention_sentiment_changes(client, text):
334
"""Track how sentiment toward entities changes across mentions."""
335
document = language_v1.Document(
336
content=text,
337
type_=language_v1.Document.Type.PLAIN_TEXT
338
)
339
340
response = client.analyze_entity_sentiment(
341
request={"document": document}
342
)
343
344
for entity in response.entities:
345
if len(entity.mentions) > 1: # Only entities with multiple mentions
346
print(f"Entity: {entity.name}")
347
print(f"Overall sentiment: {entity.sentiment.score:.2f}")
348
print("Mention progression:")
349
350
for i, mention in enumerate(entity.mentions, 1):
351
print(f" {i}. '{mention.text.content}' - Sentiment: {mention.sentiment.score:.2f}")
352
353
# Calculate sentiment trend
354
sentiment_scores = [m.sentiment.score for m in entity.mentions]
355
if len(sentiment_scores) >= 2:
356
trend = sentiment_scores[-1] - sentiment_scores[0]
357
trend_label = "improving" if trend > 0.1 else "declining" if trend < -0.1 else "stable"
358
print(f" Sentiment trend: {trend_label} ({trend:+.2f})")
359
print()
360
361
# Usage
362
text = """
363
Initially, I thought the new software was confusing and hard to use.
364
After trying the software for a week, I found it somewhat useful.
365
Now I really appreciate the software and think it's quite good.
366
"""
367
368
track_mention_sentiment_changes(client, text)
369
```
370
371
## Error Handling
372
373
```python
374
from google.api_core import exceptions
375
376
try:
377
response = client.analyze_entity_sentiment(
378
request={"document": document},
379
timeout=20.0
380
)
381
except exceptions.InvalidArgument as e:
382
print(f"Invalid request: {e}")
383
except exceptions.DeadlineExceeded:
384
print("Request timed out")
385
except exceptions.FailedPrecondition as e:
386
# This might occur if using wrong API version
387
print(f"API version error: {e}")
388
print("Note: Entity sentiment analysis requires v1 or v1beta2")
389
except exceptions.GoogleAPIError as e:
390
print(f"API error: {e}")
391
```
392
393
## Performance Considerations
394
395
- **Text Length**: Optimal for documents under 1MB
396
- **Entity Density**: Performance may vary with high entity density
397
- **Computation**: More intensive than basic entity analysis
398
- **Caching**: Results can be cached for static content
399
- **API Version**: Only available in v1 and v1beta2
400
401
## Use Cases
402
403
- **Brand Monitoring**: Track sentiment toward brands across social media and news
404
- **Product Review Analysis**: Understand customer sentiment toward product features
405
- **Political Analysis**: Monitor public sentiment toward political figures and issues
406
- **Reputation Management**: Track sentiment changes toward people or organizations
407
- **Customer Feedback**: Analyze sentiment toward specific aspects of service or products
408
- **Market Research**: Understand consumer attitudes toward competitors and market segments