-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetect-sentiment.py
47 lines (37 loc) · 1.74 KB
/
detect-sentiment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from google.cloud import language_v1
def sample_analyze_sentiment(text_content):
"""
Analyzing Sentiment in a String
Args:
text_content The text content to analyze
"""
client = language_v1.LanguageServiceClient()
# text_content = 'I am so happy and joyful.'
# Available types: PLAIN_TEXT, HTML
type_ = language_v1.Document.Type.PLAIN_TEXT
# Optional. If not specified, the language is automatically detected.
# For list of supported languages:
# https://cloud.google.com/natural-language/docs/languages
language = "en"
document = {"content": text_content, "type_": type_, "language": language}
# Available values: NONE, UTF8, UTF16, UTF32
encoding_type = language_v1.EncodingType.UTF8
response = client.analyze_sentiment(request = {'document': document, 'encoding_type': encoding_type})
# Get overall sentiment of the input document
print(u"Document sentiment score: {}".format(response.document_sentiment.score))
print(
u"Document sentiment magnitude: {}".format(
response.document_sentiment.magnitude
)
)
# Get sentiment for all sentences in the document
#for sentence in response.sentences:
# print(u"Sentence text: {}".format(sentence.text.content))
# print(u"Sentence sentiment score: {}".format(sentence.sentiment.score))
# print(u"Sentence sentiment magnitude: {}".format(sentence.sentiment.magnitude))
# Get the language of the text, which will be the same as
# the language specified in the request or, if not specified,
# the automatically-detected language.
print(u"Language of the text: {}".format(response.language))
if __name__=="__main__":
sample_analyze_sentiment("I’m going biking tomorrow.")