Skip to content

Commit bbabdfa

Browse files
committed
Refactored the Sentiment Analysis tutorial to use the Cloud Client Library.
1 parent a1b5e56 commit bbabdfa

File tree

2 files changed

+13
-19
lines changed

2 files changed

+13
-19
lines changed

language/sentiment/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
google-api-python-client==1.5.5
1+
google-cloud-language==0.22.0

language/sentiment/sentiment_analysis.py

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,32 +15,26 @@
1515

1616
import argparse
1717

18-
from googleapiclient import discovery
19-
from oauth2client.client import GoogleCredentials
18+
from google.cloud import language
2019

2120

2221
def main(movie_review_filename):
2322
"""Run a sentiment analysis request on text within a passed filename."""
24-
25-
credentials = GoogleCredentials.get_application_default()
26-
service = discovery.build('language', 'v1', credentials=credentials)
23+
language_client = language.Client()
2724

2825
with open(movie_review_filename, 'r') as review_file:
29-
service_request = service.documents().analyzeSentiment(
30-
body={
31-
'document': {
32-
'type': 'PLAIN_TEXT',
33-
'content': review_file.read(),
34-
}
35-
}
36-
)
37-
response = service_request.execute()
26+
# Instantiates a plain text document.
27+
document = language_client.document_from_html(review_file.read())
28+
29+
# Detects sentiment in the document.
30+
annotations = document.annotate_text(include_sentiment=True,
31+
include_syntax=False, include_entities=False)
3832

39-
score = response['documentSentiment']['score']
40-
magnitude = response['documentSentiment']['magnitude']
33+
score = annotations.sentiment.score
34+
magnitude = annotations.sentiment.magnitude
4135

42-
for i, sentence in enumerate(response['sentences']):
43-
sentence_sentiment = sentence['sentiment']['score']
36+
for i, sentence in enumerate(annotations.sentences):
37+
sentence_sentiment = sentence.sentiment.score
4438
print('Sentence {} has a sentiment score of {}'.format(
4539
i, sentence_sentiment))
4640

0 commit comments

Comments
 (0)