Bibliotecas cliente de Natural Language

En esta página, se muestra cómo comenzar a usar las bibliotecas cliente de Cloud para la API de Cloud Natural Language. Las bibliotecas cliente facilitan el acceso a las APIs deGoogle Cloud desde un lenguaje compatible. Si bien puedes usar las APIs deGoogle Cloud directamente mediante solicitudes sin procesar al servidor, las bibliotecas cliente proporcionan simplificaciones que reducen de manera significativa la cantidad de código que debes escribir.

Obtén más información sobre las bibliotecas cliente de Cloud y las bibliotecas cliente de las API de Google anteriores en Explicación de las bibliotecas cliente.

Instala la biblioteca cliente

C++

Consulta Configura un entorno de desarrollo de C++ para obtener detalles sobre los requisitos de esta biblioteca cliente y, luego, instala las dependencias.

C#

Si usas Visual Studio 2017 o una versión posterior, abre la ventana del administrador de paquetes de NuGet y escribe lo siguiente:

Install-Package Google.Apis

Si usas las herramientas de la interfaz de línea de comandos de .NET Core para instalar tus dependencias, ejecuta el siguiente comando:

dotnet add package Google.Apis

Para obtener más información, consulta Configura un entorno de desarrollo de C#.

Go

go get cloud.google.com/go/language/apiv1

Para obtener más información, consulta Configura un entorno de desarrollo de Go.

Java

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.56.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-language</artifactId>
  </dependency>
</dependencies>

If you are using Gradle, add the following to your dependencies:

implementation 'com.google.cloud:google-cloud-language:2.60.0'

If you are using sbt, add the following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-language" % "2.60.0"

If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Para obtener más información, consulta Configura un entorno de desarrollo de Java.

Node.js

npm install --save @google-cloud/language

Para obtener más información, consulta Configura un entorno de desarrollo de Node.js.

PHP

composer require google/apiclient

Para obtener más información, consulta PHP en Google Cloud.

Python

pip install --upgrade google-cloud-language

Para obtener más información, consulta Configura un entorno de desarrollo de Python.

Ruby

gem install google-api-client

Para obtener más información, consulta Cómo configurar un entorno de desarrollo en Ruby.

Configura la autenticación

Para autenticar las llamadas a las APIs de Google Cloud , las bibliotecas cliente admiten las credenciales predeterminadas de la aplicación (ADC). Las bibliotecas buscan credenciales en un conjunto de ubicaciones definidas y las usan para autenticar solicitudes en la API. Con ADC, puedes hacer que las credenciales estén disponibles para tu aplicación en una variedad de entornos, como el de desarrollo o producción local, sin necesidad de modificar el código de la aplicación.

Para los entornos de producción, la forma en que configuras ADC depende del servicio y el contexto. Para obtener más información, consulta Configura credenciales predeterminadas de la aplicación.

Para un entorno de desarrollo local, puedes configurar ADC con las credenciales asociadas con tu cuenta de Google:

  1. After installing the Google Cloud CLI, initialize it by running the following command:

    gcloud init

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, confirm that you have configured the gcloud CLI to use Workforce Identity Federation.

    Aparecerá una pantalla de acceso. Después de acceder, tus credenciales se almacenan en el archivo de credenciales local que usa ADC.

Usa la biblioteca cliente

El siguiente ejemplo muestra cómo usar la biblioteca cliente.

C++


#include "google/cloud/language/v2/language_client.h"
#include <iostream>

auto constexpr kText = R"""(
Four score and seven years ago our fathers brought forth on this
continent, a new nation, conceived in Liberty, and dedicated to
the proposition that all men are created equal.)""";

int main(int argc, char* argv[]) try {
  if (argc != 1) {
    std::cerr << "Usage: " << argv[0] << "\n";
    return 1;
  }

  namespace language = ::google::cloud::language_v2;
  auto client = language::LanguageServiceClient(
      language::MakeLanguageServiceConnection());

  google::cloud::language::v2::Document document;
  document.set_type(google::cloud::language::v2::Document::PLAIN_TEXT);
  document.set_content(kText);
  document.set_language_code("en-US");

  auto response = client.AnalyzeEntities(document);
  if (!response) throw std::move(response).status();

  for (auto const& entity : response->entities()) {
    if (entity.type() != google::cloud::language::v2::Entity::NUMBER) continue;
    std::cout << entity.DebugString() << "\n";
  }

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}

Go


// Sample language-quickstart uses the Google Cloud Natural API to analyze the
// sentiment of "Hello, world!".
package main

import (
	"context"
	"fmt"
	"log"

	language "cloud.google.com/go/language/apiv1"
	"cloud.google.com/go/language/apiv1/languagepb"
)

func main() {
	ctx := context.Background()

	// Creates a client.
	client, err := language.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// Sets the text to analyze.
	text := "Hello, world!"

	// Detects the sentiment of the text.
	sentiment, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
		EncodingType: languagepb.EncodingType_UTF8,
	})
	if err != nil {
		log.Fatalf("Failed to analyze text: %v", err)
	}

	fmt.Printf("Text: %v\n", text)
	if sentiment.DocumentSentiment.Score >= 0 {
		fmt.Println("Sentiment: positive")
	} else {
		fmt.Println("Sentiment: negative")
	}
}

Java

// Imports the Google Cloud client library
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.Document.Type;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.Sentiment;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    try (LanguageServiceClient language = LanguageServiceClient.create()) {

      // The text to analyze
      String text = "Hello, world!";
      Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();

      // Detects the sentiment of the text
      Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment();

      System.out.printf("Text: %s%n", text);
      System.out.printf("Sentiment: %s, %s%n", sentiment.getScore(), sentiment.getMagnitude());
    }
  }
}

Node.js

async function quickstart() {
  // Imports the Google Cloud client library
  const language = require('@google-cloud/language');

  // Instantiates a client
  const client = new language.LanguageServiceClient();

  // The text to analyze
  const text = 'Hello, world!';

  const document = {
    content: text,
    type: 'PLAIN_TEXT',
  };

  // Detects the sentiment of the text
  const [result] = await client.analyzeSentiment({document: document});
  const sentiment = result.documentSentiment;

  console.log(`Text: ${text}`);
  console.log(`Sentiment score: ${sentiment.score}`);
  console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
}

Python

# Imports the Google Cloud client library.
from google.cloud import language_v1

# Instantiates a client.
client = language_v1.LanguageServiceClient()

# The text to analyze.
text = "Hello, world!"
document = language_v1.types.Document(
    content=text, type_=language_v1.types.Document.Type.PLAIN_TEXT
)

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

print(f"Text: {text}")
print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")

Recursos adicionales

C++

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para C++:

C#

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para C#:

Go

En la siguiente lista, se incluyen vínculos a más recursos relacionados con la biblioteca cliente para Go:

Java

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para Java:

Node.js

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente de Node.js:

PHP

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para PHP:

Python

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para Python:

Ruby

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para Ruby: