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
23
+ def print_result (annotations ):
24
+ score = annotations .sentiment .score
25
+ magnitude = annotations .sentiment .magnitude
21
26
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 )
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' ]
27
+ for i , sentence in enumerate (annotations .sentences ):
28
+ sentence_sentiment = sentence .sentiment .score
44
29
print ('Sentence {} has a sentiment score of {}' .format (
45
30
i , sentence_sentiment ))
46
31
@@ -53,6 +38,19 @@ def main(movie_review_filename):
53
38
return 0
54
39
55
40
41
+ def analyze (movie_review_filename ):
42
+ """Run a sentiment analysis request on text within a passed filename."""
43
+ language_client = language .Client ()
44
+
45
+ with open (movie_review_filename , 'r' ) as review_file :
46
+ # Instantiates a plain text document.
47
+ document = language_client .document_from_html (review_file .read ())
48
+
49
+ # Detects sentiment in the document.
50
+ return document .annotate_text (include_sentiment = True ,
51
+ include_syntax = False , include_entities = False )
52
+
53
+
56
54
if __name__ == '__main__' :
57
55
parser = argparse .ArgumentParser (
58
56
description = __doc__ ,
@@ -61,4 +59,8 @@ def main(movie_review_filename):
61
59
'movie_review_filename' ,
62
60
help = 'The filename of the movie review you\' d like to analyze.' )
63
61
args = parser .parse_args ()
64
- main (args .movie_review_filename )
62
+ # Perform the analysis
63
+ annotations = analyze (args .movie_review_filename )
64
+ # Print the results
65
+ print_result (annotations )
66
+ # [END sentiment_tutorial]
0 commit comments