Skip to content

Commit ca7a29b

Browse files
jmdobryJon Wayne Parrott
authored and
Jon Wayne Parrott
committed
Refactored the Sentiment Analysis tutorial to use the Cloud Client Library. (GoogleCloudPlatform#713)
1 parent d8d7bfd commit ca7a29b

File tree

3 files changed

+36
-31
lines changed

3 files changed

+36
-31
lines changed

language/sentiment/requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
google-api-python-client==1.5.5
1+
google-cloud-language==0.22.2

language/sentiment/sentiment_analysis.py

+30-25
Original file line numberDiff line numberDiff line change
@@ -11,38 +11,24 @@
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]
1618
import 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+
5659
if __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]

language/sentiment/sentiment_analysis_test.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -13,35 +13,35 @@
1313

1414
import re
1515

16-
from sentiment_analysis import main
16+
from sentiment_analysis import analyze
1717

1818

1919
def test_pos(resource, capsys):
20-
main(resource('pos.txt'))
20+
analyze(resource('pos.txt'))
2121
out, err = capsys.readouterr()
2222
score = float(re.search('score of (.+?) with', out).group(1))
2323
magnitude = float(re.search('magnitude of (.+?)', out).group(1))
2424
assert score * magnitude > 0
2525

2626

2727
def test_neg(resource, capsys):
28-
main(resource('neg.txt'))
28+
analyze(resource('neg.txt'))
2929
out, err = capsys.readouterr()
3030
score = float(re.search('score of (.+?) with', out).group(1))
3131
magnitude = float(re.search('magnitude of (.+?)', out).group(1))
3232
assert score * magnitude < 0
3333

3434

3535
def test_mixed(resource, capsys):
36-
main(resource('mixed.txt'))
36+
analyze(resource('mixed.txt'))
3737
out, err = capsys.readouterr()
3838
score = float(re.search('score of (.+?) with', out).group(1))
3939
assert score <= 0.3
4040
assert score >= -0.3
4141

4242

4343
def test_neutral(resource, capsys):
44-
main(resource('neutral.txt'))
44+
analyze(resource('neutral.txt'))
4545
out, err = capsys.readouterr()
4646
magnitude = float(re.search('magnitude of (.+?)', out).group(1))
4747
assert magnitude <= 2.0

0 commit comments

Comments
 (0)