Google Cloud Natural Language API Client Library
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
- breaking The Natural Language API v2 introduces breaking changes, including renaming the `language` field to `language_code` in responses and removing fields like `salience` and `wikipedia_url` for entity analysis. Ensure you use the correct client (`language_v1` or `language_v2`) and adapt your code accordingly.
- gotcha Direct API Key authentication is generally not supported for Google Cloud client libraries. Attempting to use an API key might result in authentication errors.
- deprecated The direct import `from google.cloud.language import enums` is deprecated. Enums are now nested under the versioned types module (e.g., `language_v1.types.Document.Type`).
- gotcha Naming your Python script `google.py`, `language.py`, or similar names can lead to import conflicts (shadowing) with the installed `google.cloud.language` library, causing `ImportError`.
Install
-
pip install google-cloud-language
Imports
- LanguageServiceClient
from google.cloud import language_v1 client = language_v1.LanguageServiceClient()
- Document.Type
from google.cloud import language_v1 document = language_v1.types.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)
Quickstart
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.")