Natural Language-Clientbibliotheken

Auf dieser Seite werden die ersten Schritte mit den Cloud-Clientbibliotheken für die Cloud Natural Language API beschrieben. Clientbibliotheken erleichtern den Zugriff aufGoogle Cloud APIs mit einer unterstützten Sprache. Sie könnenGoogle Cloud APIs zwar direkt verwenden, indem Sie Rohanfragen an den Server senden, aber Clientbibliotheken bieten Vereinfachungen, die den zu schreibenden Code erheblich reduzieren.

Weitere Informationen zu den Cloud-Clientbibliotheken und den älteren Google API-Clientbibliotheken finden Sie unter Erläuterung zu Clientbibliotheken.

Clientbibliothek installieren

C++

Weitere Informationen zu den Anforderungen und Abhängigkeiten der Clientbibliothek finden Sie unter C++ Entwicklungsumgebung einrichten.

C#

Wenn Sie Visual Studio 2017 oder höher verwenden, öffnen Sie das Fenster „nuget package manager” und geben Sie Folgendes ein:

Install-Package Google.Apis

Wenn Sie die .NET Core-Befehlszeilentools zum Installieren der Abhängigkeiten verwenden, führen Sie den folgenden Befehl aus:

dotnet add package Google.Apis

Weitere Informationen finden Sie unter .NET-Entwicklungsumgebung einrichten.

Go

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

Weitere Informationen finden Sie unter Go-Entwicklungsumgebung einrichten.

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.

Weitere Informationen finden Sie unter Java-Entwicklungsumgebung einrichten.

Node.js

npm install --save @google-cloud/language

Weitere Informationen finden Sie unter Node.js-Entwicklungsumgebung einrichten.

PHP

composer require google/apiclient

Weitere Informationen finden Sie unter PHP auf Google Cloud verwenden.

Python

pip install --upgrade google-cloud-language

Weitere Informationen finden Sie unter Python-Entwicklungsumgebung einrichten.

Ruby

gem install google-api-client

Weitere Informationen finden Sie unter Ruby-Entwicklungsumgebung einrichten.

Authentifizierung einrichten

Zur Authentifizierung von Aufrufen an Google Cloud APIs unterstützen Clientbibliotheken Standardanmeldedaten für Anwendungen (Application Default Credentials, ADC). Die Bibliotheken suchen nach Anmeldedaten an einer Reihe von definierten Standorten und verwenden diese Anmeldedaten, um Anfragen an die API zu authentifizieren. Mit ADC können Sie Anmeldedaten für Ihre Anwendung in verschiedenen Umgebungen bereitstellen, z. B. in der lokalen Entwicklung oder Produktion, ohne den Anwendungscode ändern zu müssen.

In Produktionsumgebungen hängt die Art der Einrichtung von ADC vom Dienst und Kontext ab. Weitere Informationen finden Sie unter Standardanmeldedaten für Anwendungen einrichten.

Für eine lokale Entwicklungsumgebung können Sie ADC mit den Anmeldedaten einrichten, die Ihrem Google-Konto zugeordnet sind:

  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.

    Ein Anmeldebildschirm wird angezeigt. Nach der Anmeldung werden Ihre Anmeldedaten in der lokalen Anmeldedatendatei für ADC gespeichert.

Clientbibliothek verwenden

Das folgende Beispiel zeigt die Verwendung der Clientbibliothek.

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}")

Zusätzliche Ressourcen

C++

Die folgende Liste enthält Links zu weiteren Ressourcen im Zusammenhang mit der Clientbibliothek für C++:

C#

Die folgende Liste enthält Links zu weiteren Ressourcen im Zusammenhang mit der Clientbibliothek für C#:

Go

Die folgende Liste enthält Links zu weiteren Ressourcen im Zusammenhang mit der Clientbibliothek für Go:

Java

Die folgende Liste enthält Links zu weiteren Ressourcen im Zusammenhang mit der Clientbibliothek für Java:

Node.js

Die folgende Liste enthält Links zu weiteren Ressourcen im Zusammenhang mit der Clientbibliothek für Node.js:

PHP

Die folgende Liste enthält Links zu weiteren Ressourcen im Zusammenhang mit der Clientbibliothek für PHP:

Python

Die folgende Liste enthält Links zu weiteren Ressourcen im Zusammenhang mit der Clientbibliothek für Python:

Ruby

Die folgende Liste enthält Links zu weiteren Ressourcen im Zusammenhang mit der Clientbibliothek für Ruby: