Sentiment Analysis Tutorial

Audience

This tutorial is designed to let you quickly start exploring and developing applications with the Google Cloud Natural Language API. It is designed for people familiar with basic programming, though even without much programming knowledge, you should be able to follow along. Having walked through this tutorial, you should be able to use the Reference documentation to create your own basic applications.

This tutorial steps through a Natural Language API application using Python code. The purpose here is not to explain the Python client libraries, but to explain how to make calls to the Natural Language API. Applications in Java and Node.js are essentially similar. Consult the Natural Language API Samples for samples in other languages (including this sample within the tutorial).

Prerequisites

This tutorial has several prerequisites:

Analyzing document sentiment

This tutorial walks you through a basic Natural Language API application, using an analyzeSentiment request, which performs sentiment analysis on text. Sentiment analysis attempts to determine the overall attitude (positive or negative) and is represented by numerical score and magnitude values. (For more information on these concepts, consult Natural Language Basics.)

We'll show the entire code first. (Note that we have removed most comments from this code in order to show you how brief it is. We'll provide more comments as we walk through the code.)

For more information on installing and using the Google Cloud Natural Language Client Library for Python, see Natural Language API Client Libraries.
"""Demonstrates how to make a simple call to the Natural Language API."""

import argparse

from google.cloud import language_v1



def print_result(annotations):
    score = annotations.document_sentiment.score
    magnitude = annotations.document_sentiment.magnitude

    for index, sentence in enumerate(annotations.sentences):
        sentence_sentiment = sentence.sentiment.score
        print(f"Sentence {index} has a sentiment score of {sentence_sentiment}")

    print(f"Overall Sentiment: score of {score} with magnitude of {magnitude}")
    return 0




def analyze(movie_review_filename):
    """Run a sentiment analysis request on text within a passed filename."""
    client = language_v1.LanguageServiceClient()

    with open(movie_review_filename) as review_file:
        # Instantiates a plain text document.
        content = review_file.read()

    document = language_v1.Document(
        content=content, type_=language_v1.Document.Type.PLAIN_TEXT
    )
    annotations = client.analyze_sentiment(request={"document": document})

    # Print the results
    print_result(annotations)




if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        "movie_review_filename",
        help="The filename of the movie review you'd like to analyze.",
    )
    args = parser.parse_args()

    analyze(args.movie_review_filename)

This simple application performs the following tasks:

  • Imports the libraries necessary to run the application
  • Takes a text file and passes it to the main() function
  • Reads the text file and makes a request to the service
  • Parses the response from the service and displays it to the user

We'll go over these steps in more detail below.

Importing libraries

For more information on installing and using the Google Cloud Natural Language Client Library for Python, see Natural Language API Client Libraries.
import argparse

from google.cloud import language_v1

We import argparse, a standard library, to allow the application to accept input filenames as arguments.

For using the Cloud Natural Language API, we'll also want to import the language module from the google-cloud-language library. The types module contains classes that are required for creating requests.

Running your application

if __name__ ==