|
15 | 15 |
|
16 | 16 | import argparse
|
17 | 17 |
|
18 |
| -from googleapiclient import discovery |
19 |
| -from oauth2client.client import GoogleCredentials |
| 18 | +from google.cloud import language |
20 | 19 |
|
21 | 20 |
|
22 | 21 | def main(movie_review_filename):
|
23 | 22 | """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() |
27 | 24 |
|
28 | 25 | 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) |
38 | 32 |
|
39 |
| - score = response['documentSentiment']['score'] |
40 |
| - magnitude = response['documentSentiment']['magnitude'] |
| 33 | + score = annotations.sentiment.score |
| 34 | + magnitude = annotations.sentiment.magnitude |
41 | 35 |
|
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 |
44 | 38 | print('Sentence {} has a sentiment score of {}'.format(
|
45 | 39 | i, sentence_sentiment))
|
46 | 40 |
|
|
0 commit comments