Library klien Natural Language

Halaman ini menunjukkan cara memulai Library Klien Cloud untuk Cloud Natural Language API. Library klien mempermudah akses Google Cloud API dari bahasa yang didukung. Meskipun Anda dapat menggunakan Google Cloud API secara langsung dengan membuat permintaan mentah ke server, library klien memberikan penyederhanaan yang secara signifikan mengurangi jumlah kode yang perlu Anda tulis.

Baca selengkapnya tentang Library Klien Cloud dan Library Klien Google API yang lebih lama di Penjelasan library klien.

Menginstal library klien

C++

Lihat Menyiapkan lingkungan pengembangan C++ untuk mengetahui detail tentang persyaratan library klien ini dan menginstal dependensi.

C#

Jika Anda menggunakan Visual Studio 2017 atau versi yang lebih baru, buka jendela pengelola paket nuget dan ketikkan berikut ini:

Install-Package Google.Apis

Jika Anda menggunakan alat antarmuka command line .NET Core untuk menginstal dependensi, jalankan perintah berikut:

dotnet add package Google.Apis

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan C#.

Go

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

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan 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.55.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.59.0'

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

libraryDependencies += "com.google.cloud" % "google-cloud-language" % "2.59.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.

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Java.

Node.js

npm install --save @google-cloud/language

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Node.js.

PHP

composer require google/apiclient

Untuk informasi selengkapnya, lihat Menggunakan PHP di Google Cloud.

Python

pip install --upgrade google-cloud-language

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Python.

Ruby

gem install google-api-client

Untuk informasi selengkapnya, lihat Menyiapkan Lingkungan Pengembangan Ruby.

Menyiapkan autentikasi

Untuk mengautentikasi panggilan ke Google Cloud API, library klien mendukung Kredensial Default Aplikasi (ADC); library ini mencari kredensial dalam kumpulan lokasi yang ditentukan dan menggunakan kredensial tersebut untuk mengautentikasi permintaan ke API. Dengan ADC, Anda dapat menyediakan kredensial untuk aplikasi di berbagai lingkungan, seperti pengembangan lokal atau produksi, tanpa perlu mengubah kode aplikasi.

Untuk lingkungan produksi, cara Anda menyiapkan ADC bergantung pada layanan dan konteks. Untuk informasi selengkapnya, lihat Menyiapkan Kredensial Default Aplikasi.

Untuk lingkungan pengembangan lokal, Anda dapat menyiapkan ADC dengan kredensial yang terkait dengan Akun Google Anda:

  1. Install the Google Cloud CLI, then initialize it by running the following command:

    gcloud init
  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.

    Layar login akan muncul. Setelah Anda login, kredensial Anda disimpan dalam file kredensial lokal yang digunakan oleh ADC.

Menggunakan library klien

Contoh berikut menunjukkan cara menggunakan library klien.

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

Referensi lainnya

C++

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk C++:

C#

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk C#:

Go

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk Go:

Java

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk Java:

Node.js

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk Node.js:

PHP

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk PHP:

Python

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk Python:

Ruby

Daftar berikut berisi link ke referensi lainnya yang terkait dengan library klien untuk Ruby: