1111# See the License for the specific language governing permissions and
1212# limitations under the License.
1313
14+ # [START sentiment_tutorial]
1415"""Demonstrates how to make a simple call to the Natural Language API."""
1516
17+ # [START sentiment_tutorial_import]
1618import argparse
1719
18- from googleapiclient import discovery
19- from oauth2client . client import GoogleCredentials
20+ from google . cloud import language
21+ # [END sentiment_tutorial_import]
2022
2123
22- def main (movie_review_filename ):
23- """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 )
24+ def print_result (annotations ):
25+ score = annotations .sentiment .score
26+ magnitude = annotations .sentiment .magnitude
2727
28- 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 ()
38-
39- score = response ['documentSentiment' ]['score' ]
40- magnitude = response ['documentSentiment' ]['magnitude' ]
41-
42- for i , sentence in enumerate (response ['sentences' ]):
43- sentence_sentiment = sentence ['sentiment' ]['score' ]
28+ for index , sentence in enumerate (annotations .sentences ):
29+ sentence_sentiment = sentence .sentiment .score
4430 print ('Sentence {} has a sentiment score of {}' .format (
45- i , sentence_sentiment ))
31+ index , sentence_sentiment ))
4632
4733 print ('Overall Sentiment: score of {} with magnitude of {}' .format (
4834 score , magnitude ))
@@ -53,6 +39,23 @@ def main(movie_review_filename):
5339 return 0
5440
5541
42+ def analyze (movie_review_filename ):
43+ """Run a sentiment analysis request on text within a passed filename."""
44+ language_client = language .Client ()
45+
46+ with open (movie_review_filename , 'r' ) as review_file :
47+ # Instantiates a plain text document.
48+ document = language_client .document_from_html (review_file .read ())
49+
50+ # Detects sentiment in the document.
51+ annotations = document .annotate_text (include_sentiment = True ,
52+ include_syntax = False ,
53+ include_entities = False )
54+
55+ # Print the results
56+ print_result (annotations )
57+
58+
5659if __name__ == '__main__' :
5760 parser = argparse .ArgumentParser (
5861 description = __doc__ ,
@@ -61,4 +64,6 @@ def main(movie_review_filename):
6164 'movie_review_filename' ,
6265 help = 'The filename of the movie review you\' d like to analyze.' )
6366 args = parser .parse_args ()
64- main (args .movie_review_filename )
67+
68+ analyze (args .movie_review_filename )
69+ # [END sentiment_tutorial]
0 commit comments