GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Refactored the Sentiment Analysis tutorial to use the Cloud Client Lib by jmdobry · Pull Request #713 · GoogleCloudPlatform/python-docs-samples

Refactored the Sentiment Analysis tutorial to use the Cloud Client Lib #713

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
theacodes merged 1 commit into master from sentiment-analysis
Dec 15, 2016

Uh oh!

There was an error while loading. Please reload this page.

Merged

Refactored the Sentiment Analysis tutorial to use the Cloud Client Lib #713

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
1 commit
Select commit
348ff53
Refactored the Sentiment Analysis tutorial to use the Cloud Client Li…
jmdobry Dec 12, 2016
File filter
Filter by extension


Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

2 changes: 1 addition & 1 deletion 2 language/sentiment/requirements.txt
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1 +1 @@
google-api-python-client==1.5.5
google-cloud-language==0.22.2
55 changes: 30 additions & 25 deletions 55 language/sentiment/sentiment_analysis.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,24 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# [START sentiment_tutorial]
"""Demonstrates how to make a simple call to the Natural Language API."""

# [START sentiment_tutorial_import]
import argparse

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.cloud import language
# [END sentiment_tutorial_import]


def main(movie_review_filename):
"""Run a sentiment analysis request on text within a passed filename."""

credentials = GoogleCredentials.get_application_default()
service = discovery.build('language', 'v1', credentials=credentials)
def print_result(annotations):
score = annotations.sentiment.score
magnitude = annotations.sentiment.magnitude

with open(movie_review_filename, 'r') as review_file:
service_request = service.documents().analyzeSentiment(
body={
'document': {
'type': 'PLAIN_TEXT',
'content': review_file.read(),
}
}
)
response = service_request.execute()

score = response['documentSentiment']['score']
magnitude = response['documentSentiment']['magnitude']

for i, sentence in enumerate(response['sentences']):
sentence_sentiment = sentence['sentiment']['score']
for index, sentence in enumerate(annotations.sentences):
sentence_sentiment = sentence.sentiment.score
print('Sentence {} has a sentiment score of {}'.format(
i, sentence_sentiment))
index, sentence_sentiment))

print('Overall Sentiment: score of {} with magnitude of {}'.format(
score, magnitude))
Expand All @@ -53,6 +39,23 @@ def main(movie_review_filename):
return 0


def analyze(movie_review_filename):
"""Run a sentiment analysis request on text within a passed filename."""
language_client = language.Client()

with open(movie_review_filename, 'r') as review_file:
# Instantiates a plain text document.
document = language_client.document_from_html(review_file.read())

# Detects sentiment in the document.
annotations = document.annotate_text(include_sentiment=True,
include_syntax=False,
include_entities=False)

# Print the results
print_result(annotations)


if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
Expand All @@ -61,4 +64,6 @@ def main(movie_review_filename):
'movie_review_filename',
help='The filename of the movie review you\'d like to analyze.')
args = parser.parse_args()
main(args.movie_review_filename)

analyze(args.movie_review_filename)
# [END sentiment_tutorial]
10 changes: 5 additions & 5 deletions 10 language/sentiment/sentiment_analysis_test.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,35 @@

import re

from sentiment_analysis import main
from sentiment_analysis import analyze


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


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


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


def test_neutral(resource, capsys):
main(resource('neutral.txt'))
analyze(resource('neutral.txt'))
out, err = capsys.readouterr()
magnitude = float(re.search('magnitude of (.+?)', out).group(1))
assert magnitude <= 2.0
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.