Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit e8a10bf

Browse filesBrowse files
jerjouJon Wayne Parrott
authored andcommitted
Add sentiment analysis sample (GoogleCloudPlatform#533)
* Add sentiment analysis sample * Move sample review files into resources directory * Remove blank line from end of file * Update set up instructions to point to getting started guide * Update README to remove need to set up gcloud. Itemize what setting up a project entails. * Update NL README to link to Sentiment tutorial code * Coerce number types before comparison
1 parent faa6c54 commit e8a10bf
Copy full SHA for e8a10bf

File tree

Expand file treeCollapse file tree

9 files changed

+192
-0
lines changed
Filter options
Expand file treeCollapse file tree

9 files changed

+192
-0
lines changed

‎language/README.md

Copy file name to clipboardExpand all lines: language/README.md
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,9 @@ to extract text from images, then uses the NL API to extract entity information
1313
from those texts, and stores the extracted information in a database in support
1414
of further analysis and correlation.
1515

16+
- [sentiment](sentiment) contains the [Sentiment Analysis
17+
Tutorial](https://cloud.google.com/natural-language/docs/sentiment-tutorial)
18+
code as used within the documentation.
19+
1620
- [syntax_triples](syntax_triples) uses syntax analysis to find
1721
subject-verb-object triples in a given piece of text.

‎language/sentiment/README.md

Copy file name to clipboard
+48Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Introduction
2+
3+
This sample contains the code referenced in the
4+
[Sentiment Analysis Tutorial](http://cloud.google.com/natural-language/docs/sentiment-tutorial)
5+
within the Google Cloud Natural Language API Documentation. A full walkthrough of this sample
6+
is located within the documentation.
7+
8+
This sample is a simple illustration of how to construct a sentiment analysis
9+
request and process a response using the API.
10+
11+
## Prerequisites
12+
13+
Set up your
14+
[Cloud Natural Language API project](https://cloud.google.com/natural-language/docs/getting-started#set_up_a_project)
15+
, which includes:
16+
17+
* Enabling the Natural Language API
18+
* Setting up a service account
19+
* Ensuring you've properly set up your `GOOGLE_APPLICATION_CREDENTIALS` for proper
20+
authentication to the service.
21+
22+
## Download the Code
23+
24+
```
25+
$ git clone https://github.com/GoogleCloudPlatform/python-dev-samples/language/sentiment/
26+
$ cd python-docs-samples/language/sentiment
27+
```
28+
29+
## Run the Code
30+
31+
Open a sample folder, create a virtualenv, install dependencies, and run the sample:
32+
33+
```
34+
$ virtualenv env
35+
$ source env/bin/activate
36+
(env)$ pip install -r requirements.txt
37+
```
38+
39+
### Usage
40+
41+
This sample provides four sample movie reviews which you can
42+
provide to the sample on the command line. (You can also
43+
pass your own text files.)
44+
45+
```
46+
(env)$ python sentiment_analysis.py textfile.txt
47+
Sentiment: polarity of -0.1 with magnitude of 6.7
48+
```

‎language/sentiment/requirements.txt

Copy file name to clipboard
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
google-api-python-client==1.5.3
2+
+20Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
I really wanted to love 'Bladerunner' but ultimately I couldn't get
2+
myself to appreciate it fully. However, you may like it if you're into
3+
science fiction, especially if you're interested in the philosophical
4+
exploration of what it means to be human or machine. Some of the gizmos
5+
like the flying cars and the Vouight-Kampff machine (which seemed very
6+
steampunk), were quite cool.
7+
8+
I did find the plot pretty slow and but the dialogue and action sequences
9+
were good. Unlike most science fiction films, this one was mostly quiet, and
10+
not all that much happened, except during the last 15 minutes. I didn't
11+
understand why a unicorn was in the movie. The visual effects were fantastic,
12+
however, and the musical score and overall mood was quite interesting.
13+
A futurist Los Angeles that was both highly polished and also falling apart
14+
reminded me of 'Outland.' Certainly, the style of the film made up for
15+
many of its pedantic plot holes.
16+
17+
If you want your sci-fi to be lasers and spaceships, 'Bladerunner' may
18+
disappoint you. But if you want it to make you think, this movie may
19+
be worth the money.
20+

‎language/sentiment/resources/neg.txt

Copy file name to clipboard
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
What was Hollywood thinking with this movie! I hated,
2+
hated, hated it. BORING! I went afterwards and demanded my money back.
3+
They refused.
4+
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
I neither liked nor disliked this movie. Parts were interesting, but
2+
overall I was left wanting more. The acting was pretty good.
3+

‎language/sentiment/resources/pos.txt

Copy file name to clipboard
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
`Bladerunner` is often touted as one of the best science fiction films ever
2+
made. Indeed, it satisfies many of the requisites for good sci-fi: a future
3+
world with flying cars and humanoid robots attempting to rebel against their
4+
creators. But more than anything, `Bladerunner` is a fantastic exploration
5+
of the nature of what it means to be human. If we create robots which can
6+
think, will they become human? And if they do, what makes us unique? Indeed,
7+
how can we be sure we're not human in any case? `Bladerunner` explored
8+
these issues before such movies as `The Matrix,' and did so intelligently.
9+
The visual effects and score by Vangelis set the mood. See this movie
10+
in a dark theatre to appreciate it fully. Highly recommended!
11+
+54Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Copyright 2016, Google, Inc.
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
14+
'''Demonstrates how to make a simple call to the Natural Language API'''
15+
16+
import argparse
17+
from googleapiclient import discovery
18+
from oauth2client.client import GoogleCredentials
19+
20+
21+
def main(movie_review_filename):
22+
'''Run a sentiment analysis request on text within a passed filename.'''
23+
24+
credentials = GoogleCredentials.get_application_default()
25+
service = discovery.build('language', 'v1beta1', credentials=credentials)
26+
27+
with open(movie_review_filename, 'r') as review_file:
28+
service_request = service.documents().analyzeSentiment(
29+
body={
30+
'document': {
31+
'type': 'PLAIN_TEXT',
32+
'content': review_file.read(),
33+
}
34+
}
35+
)
36+
response = service_request.execute()
37+
38+
polarity = response['documentSentiment']['polarity']
39+
magnitude = response['documentSentiment']['magnitude']
40+
41+
print('Sentiment: polarity of {} with magnitude of {}'.format(
42+
polarity, magnitude))
43+
return 0
44+
45+
46+
if __name__ == '__main__':
47+
parser = argparse.ArgumentParser(
48+
description=__doc__,
49+
formatter_class=argparse.RawDescriptionHelpFormatter)
50+
parser.add_argument(
51+
'movie_review_filename',
52+
help='The filename of the movie review you\'d like to analyze.')
53+
args = parser.parse_args()
54+
main(args.movie_review_filename)
+46Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Copyright 2016, Google, Inc.
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
14+
import re
15+
from sentiment_analysis import main
16+
17+
18+
def test_pos(resource, capsys):
19+
main(resource('pos.txt'))
20+
out, err = capsys.readouterr()
21+
polarity = float(re.search('polarity of (.+?) with', out).group(1))
22+
magnitude = float(re.search('magnitude of (.+?)', out).group(1))
23+
assert polarity * magnitude > 0
24+
25+
26+
def test_neg(resource, capsys):
27+
main(resource('neg.txt'))
28+
out, err = capsys.readouterr()
29+
polarity = float(re.search('polarity of (.+?) with', out).group(1))
30+
magnitude = float(re.search('magnitude of (.+?)', out).group(1))
31+
assert polarity * magnitude < 0
32+
33+
34+
def test_mixed(resource, capsys):
35+
main(resource('mixed.txt'))
36+
out, err = capsys.readouterr()
37+
polarity = float(re.search('polarity of (.+?) with', out).group(1))
38+
assert polarity <= 0.3
39+
assert polarity >= -0.3
40+
41+
42+
def test_neutral(resource, capsys):
43+
main(resource('neutral.txt'))
44+
out, err = capsys.readouterr()
45+
magnitude = float(re.search('magnitude of (.+?)', out).group(1))
46+
assert magnitude <= 2.0

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.