|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2016 Google, Inc |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# [START full_tutorial_script] |
| 17 | +# [START import_libraries] |
| 18 | +import argparse |
| 19 | +import io |
| 20 | + |
| 21 | +from googleapiclient import discovery |
| 22 | +from oauth2client.client import GoogleCredentials |
| 23 | +# [END import_libraries] |
| 24 | + |
| 25 | + |
| 26 | +def print_sentiment(filename): |
| 27 | + """Prints sentiment analysis on a given file contents.""" |
| 28 | + # [START authenticating_to_the_api] |
| 29 | + credentials = GoogleCredentials.get_application_default() |
| 30 | + service = discovery.build('language', 'v1', credentials=credentials) |
| 31 | + # [END authenticating_to_the_api] |
| 32 | + |
| 33 | + # [START constructing_the_request] |
| 34 | + with io.open(filename, 'r') as review_file: |
| 35 | + review_file_contents = review_file.read() |
| 36 | + |
| 37 | + service_request = service.documents().analyzeSentiment( |
| 38 | + body={ |
| 39 | + 'document': { |
| 40 | + 'type': 'PLAIN_TEXT', |
| 41 | + 'content': review_file_contents, |
| 42 | + } |
| 43 | + } |
| 44 | + ) |
| 45 | + response = service_request.execute() |
| 46 | + # [END constructing_the_request] |
| 47 | + |
| 48 | + # [START parsing_the_response] |
| 49 | + score = response['documentSentiment']['score'] |
| 50 | + magnitude = response['documentSentiment']['magnitude'] |
| 51 | + |
| 52 | + for n, sentence in enumerate(response['sentences']): |
| 53 | + sentence_sentiment = sentence['sentiment']['score'] |
| 54 | + print('Sentence {} has a sentiment score of {}'.format(n, |
| 55 | + sentence_sentiment)) |
| 56 | + |
| 57 | + print('Overall Sentiment: score of {} with magnitude of {}'.format( |
| 58 | + score, magnitude)) |
| 59 | + # [END parsing_the_response] |
| 60 | + |
| 61 | + |
| 62 | +# [START running_your_application] |
| 63 | +if __name__ == '__main__': |
| 64 | + parser = argparse.ArgumentParser() |
| 65 | + parser.add_argument( |
| 66 | + 'movie_review_filename', |
| 67 | + help='The filename of the movie review you\'d like to analyze.') |
| 68 | + args = parser.parse_args() |
| 69 | + print_sentiment(args.movie_review_filename) |
| 70 | +# [END running_your_application] |
| 71 | +# [END full_tutorial_script] |
0 commit comments