11
11
# See the License for the specific language governing permissions and
12
12
# limitations under the License.
13
13
14
+ # [START sentiment_tutorial]
14
15
"""Demonstrates how to make a simple call to the Natural Language API."""
15
16
17
+ # [START sentiment_tutorial_import]
16
18
import argparse
17
19
18
- from googleapiclient import discovery
19
- from oauth2client . client import GoogleCredentials
20
+ from google . cloud import language
21
+ # [END sentiment_tutorial_import]
20
22
21
23
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
27
27
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
44
30
print ('Sentence {} has a sentiment score of {}' .format (
45
- i , sentence_sentiment ))
31
+ index , sentence_sentiment ))
46
32
47
33
print ('Overall Sentiment: score of {} with magnitude of {}' .format (
48
34
score , magnitude ))
@@ -53,6 +39,23 @@ def main(movie_review_filename):
53
39
return 0
54
40
55
41
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
+
56
59
if __name__ == '__main__' :
57
60
parser = argparse .ArgumentParser (
58
61
description = __doc__ ,
@@ -61,4 +64,6 @@ def main(movie_review_filename):
61
64
'movie_review_filename' ,
62
65
help = 'The filename of the movie review you\' d like to analyze.' )
63
66
args = parser .parse_args ()
64
- main (args .movie_review_filename )
67
+
68
+ analyze (args .movie_review_filename )
69
+ # [END sentiment_tutorial]
0 commit comments