Google Cloud Natural Language API Client Library

2.20.0 · active · verified Sat Mar 28

The `google-cloud-language` library provides a Python client for the Google Cloud Natural Language API. It enables developers to perform sentiment analysis, entity analysis, entity sentiment analysis, content classification, and syntax analysis on text. This library is part of the larger `google-cloud-python` monorepo, meaning it receives regular updates and patches as part of Google Cloud's client library ecosystem, with frequent releases for individual services.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to perform sentiment analysis using the `google-cloud-language` library. It initializes the client and sends a text document for sentiment detection. Ensure your Google Cloud project has the Natural Language API enabled and that you've set up authentication, preferably using Application Default Credentials, for local development or deployed applications.

import os
from google.cloud import language_v1

# Set up Application Default Credentials if running locally
# This line is usually not needed when running on Google Cloud services (e.g., Compute Engine, Cloud Run)
# For local development, ensure GOOGLE_APPLICATION_CREDENTIALS points to a service account key file
# or run `gcloud auth application-default login`
# os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', '')

def analyze_sentiment(text_content):
    """Analyzes the sentiment of the provided text."""
    client = language_v1.LanguageServiceClient()

    # Available document types: PLAIN_TEXT, HTML
    document = language_v1.types.Document(
        content=text_content, type_=language_v1.Document.Type.PLAIN_TEXT
    )

    # Detects the sentiment of the document
    sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment

    print(f"Text: {text_content}")
    print(f"Sentiment Score: {sentiment.score}")
    print(f"Sentiment Magnitude: {sentiment.magnitude}")

# Example usage
if __name__ == '__main__':
    analyze_sentiment("Hello, world! This is a great day.")
    analyze_sentiment("I am very unhappy with the service.")

view raw JSON →