0
# Sentiment Analysis
1
2
Analyzes the emotional tone and attitude in text content, providing sentiment scores and magnitude measurements to understand how positive, negative, or neutral the text is. Sentiment analysis is useful for understanding customer feedback, social media content, reviews, and any text where emotional context matters.
3
4
## Capabilities
5
6
### Analyze Sentiment
7
8
Performs sentiment analysis on the provided text, returning overall document sentiment and per-sentence sentiment scores.
9
10
```python { .api }
11
def analyze_sentiment(
12
self,
13
request: Optional[Union[AnalyzeSentimentRequest, dict]] = None,
14
*,
15
document: Optional[Document] = None,
16
encoding_type: Optional[EncodingType] = None,
17
retry: OptionalRetry = gapic_v1.method.DEFAULT,
18
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
19
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
20
) -> AnalyzeSentimentResponse:
21
"""
22
Analyzes the sentiment of the provided text.
23
24
Args:
25
request: The request object containing document and options
26
document: Input document for analysis
27
encoding_type: Text encoding type for offset calculations
28
retry: Retry configuration for the request
29
timeout: Request timeout in seconds
30
metadata: Additional metadata to send with the request
31
32
Returns:
33
AnalyzeSentimentResponse containing sentiment analysis results
34
"""
35
```
36
37
#### Usage Example
38
39
```python
40
from google.cloud import language
41
42
# Initialize client
43
client = language.LanguageServiceClient()
44
45
# Create document
46
document = language.Document(
47
content="I love this product! It's absolutely fantastic and works perfectly.",
48
type_=language.Document.Type.PLAIN_TEXT
49
)
50
51
# Analyze sentiment
52
response = client.analyze_sentiment(
53
request={"document": document}
54
)
55
56
# Access overall document sentiment
57
document_sentiment = response.document_sentiment
58
print(f"Document sentiment score: {document_sentiment.score}")
59
print(f"Document sentiment magnitude: {document_sentiment.magnitude}")
60
61
# Access per-sentence sentiment
62
for i, sentence in enumerate(response.sentences):
63
print(f"Sentence {i}: {sentence.text.content}")
64
print(f" Sentiment score: {sentence.sentiment.score}")
65
print(f" Sentiment magnitude: {sentence.sentiment.magnitude}")
66
```
67
68
## Request and Response Types
69
70
### AnalyzeSentimentRequest
71
72
```python { .api }
73
class AnalyzeSentimentRequest:
74
document: Document
75
encoding_type: EncodingType
76
```
77
78
### AnalyzeSentimentResponse
79
80
```python { .api }
81
class AnalyzeSentimentResponse:
82
document_sentiment: Sentiment
83
language: str
84
sentences: MutableSequence[Sentence]
85
```
86
87
## Supporting Types
88
89
### Sentiment
90
91
Represents sentiment analysis results with score and magnitude values.
92
93
```python { .api }
94
class Sentiment:
95
magnitude: float # Range: [0.0, +inf) - Emotional intensity
96
score: float # Range: [-1.0, 1.0] - Positive/negative polarity
97
```
98
99
**Score Interpretation:**
100
- Positive values (0.25 to 1.0): Positive sentiment
101
- Near zero (-0.25 to 0.25): Neutral sentiment
102
- Negative values (-1.0 to -0.25): Negative sentiment
103
104
**Magnitude Interpretation:**
105
- Low magnitude (0.0 to 0.5): Weak emotional intensity
106
- Medium magnitude (0.5 to 1.5): Moderate emotional intensity
107
- High magnitude (1.5+): Strong emotional intensity
108
109
### Sentence
110
111
Represents an individual sentence with its sentiment analysis.
112
113
```python { .api }
114
class Sentence:
115
text: TextSpan
116
sentiment: Sentiment
117
```
118
119
### TextSpan
120
121
Represents a span of text with content and position information.
122
123
```python { .api }
124
class TextSpan:
125
content: str
126
begin_offset: int
127
```
128
129
## Advanced Usage
130
131
### Batch Sentiment Analysis
132
133
```python
134
def analyze_multiple_texts(client, texts):
135
"""Analyze sentiment for multiple text samples."""
136
results = []
137
138
for text in texts:
139
document = language.Document(
140
content=text,
141
type_=language.Document.Type.PLAIN_TEXT
142
)
143
144
response = client.analyze_sentiment(
145
request={"document": document}
146
)
147
148
results.append({
149
'text': text,
150
'score': response.document_sentiment.score,
151
'magnitude': response.document_sentiment.magnitude
152
})
153
154
return results
155
156
# Usage
157
texts = [
158
"This is amazing!",
159
"I hate this product.",
160
"It's okay, nothing special."
161
]
162
163
results = analyze_multiple_texts(client, texts)
164
for result in results:
165
print(f"Text: {result['text']}")
166
print(f"Score: {result['score']}, Magnitude: {result['magnitude']}")
167
```
168
169
### HTML Content Analysis
170
171
```python
172
# Analyze sentiment in HTML content
173
html_content = """
174
<html>
175
<body>
176
<h1>Product Review</h1>
177
<p>This product is <strong>absolutely wonderful</strong>!
178
I would definitely recommend it to anyone.</p>
179
</body>
180
</html>
181
"""
182
183
document = language.Document(
184
content=html_content,
185
type_=language.Document.Type.HTML
186
)
187
188
response = client.analyze_sentiment(
189
request={"document": document}
190
)
191
192
print(f"HTML sentiment score: {response.document_sentiment.score}")
193
```
194
195
### Encoding Type Usage
196
197
```python
198
# When you need character offset information for UTF-16 encoded text
199
document = language.Document(
200
content="感情分析のテスト", # Japanese text
201
type_=language.Document.Type.PLAIN_TEXT
202
)
203
204
response = client.analyze_sentiment(
205
request={
206
"document": document,
207
"encoding_type": language.EncodingType.UTF16
208
}
209
)
210
211
# Offsets will be calculated based on UTF-16 encoding
212
for sentence in response.sentences:
213
print(f"Sentence: {sentence.text.content}")
214
print(f"UTF-16 offset: {sentence.text.begin_offset}")
215
```
216
217
### Error Handling
218
219
```python
220
from google.api_core import exceptions
221
222
try:
223
response = client.analyze_sentiment(
224
request={"document": document},
225
timeout=10.0
226
)
227
except exceptions.InvalidArgument as e:
228
print(f"Invalid request: {e}")
229
except exceptions.DeadlineExceeded:
230
print("Request timed out")
231
except exceptions.GoogleAPIError as e:
232
print(f"API error: {e}")
233
```
234
235
## Performance Considerations
236
237
- **Text Length**: Optimal performance for texts under 1MB
238
- **Language Support**: Best results with supported languages (auto-detected or specified)
239
- **Batch Processing**: For multiple documents, consider using async client
240
- **Caching**: Results can be cached as sentiment typically doesn't change for static text
241
242
## Language Support
243
244
The API automatically detects language but works best with:
245
- English
246
- Spanish
247
- French
248
- German
249
- Italian
250
- Portuguese
251
- Russian
252
- Japanese
253
- Korean
254
- Chinese (Simplified and Traditional)
255
256
Specify document language for better accuracy:
257
258
```python
259
document = language.Document(
260
content="Esto es fantástico!",
261
type_=language.Document.Type.PLAIN_TEXT,
262
language="es" # Spanish
263
)
264
```