Esta página foi traduzida pela API Cloud Translation.
Switch to English

Listar glossários (somente na edição Advanced)

Liste todos os glossários de um determinado projeto.

Páginas de documentação que incluem esta amostra de código

Para visualizar o exemplo de código usado em contexto, consulte a seguinte documentação:

Amostra de código

C#

Antes de testar esta amostra, siga as instruções de configuração para C# no Guia de início rápido do Translation: como usar bibliotecas de cliente. Saiba mais na documentação de referência da API Translation para C#.


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class ListGlossary
    {
        /// <summary>
        /// Lists all the glossaries for a given project.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void ListGlossariesSample(string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            ListGlossariesRequest request = new ListGlossariesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
            };
            PagedEnumerable<ListGlossariesResponse, Glossary> response = translationServiceClient.ListGlossaries(request);
            // Iterate over glossaries and display each glossary's details.
            foreach (Glossary item in response)
            {
                Console.WriteLine($"Glossary name: {item.Name}");
                Console.WriteLine($"Entry count: {item.EntryCount}");
                Console.WriteLine($"Input URI: {item.InputConfig.GcsSource.InputUri}");
            }
        }
    }

Go

Antes de testar esta amostra, siga as instruções de configuração para Go no Guia de início rápido do Translation: como usar bibliotecas de cliente. Saiba mais na documentação de referência da API Translation para Go.

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	"google.golang.org/api/iterator"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// listGlossaries gets the specified glossary.
func listGlossaries(w io.Writer, projectID string, location string) error {
	// projectID := "my-project-id"
	// location := "us-central1"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.ListGlossariesRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListGlossaries(ctx, req)

	// Iterate over all results
	for {
		glossary, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListGlossaries.Next: %v", err)
		}
		fmt.Fprintf(w, "Name: %v\n", glossary.GetName())
		fmt.Fprintf(w, "Entry count: %v\n", glossary.GetEntryCount())
		fmt.Fprintf(w, "Input URI: %v\n", glossary.GetInputConfig().GetGcsSource().GetInputUri())
		for _, languageCode := range glossary.GetLanguageCodesSet().GetLanguageCodes() {
			fmt.Fprintf(w, "Language code: %v\n", languageCode)
		}
		if languagePair := glossary.GetLanguagePair(); languagePair != nil {
			fmt.Fprintf(w, "Language pair: %v, %v\n",
				languagePair.GetSourceLanguageCode(), languagePair.GetTargetLanguageCode())
		}
	}

	return nil
}

Java

Antes de testar esta amostra, siga as instruções de configuração para Java no Guia de início rápido do Translation: como usar bibliotecas de cliente. Saiba mais na documentação de referência da API Translation para Java.

import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.ListGlossariesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class ListGlossaries {

  public static void listGlossaries() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    listGlossaries(projectId);
  }

  // List all the glossaries in a specified location
  public static void listGlossaries(String projectId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "us-central1");
      ListGlossariesRequest request =
          ListGlossariesRequest.newBuilder().setParent(parent.toString()).build();

      for (Glossary responseItem : client.listGlossaries(request).iterateAll()) {
        System.out.printf("Glossary name: %s\n", responseItem.getName());
        System.out.printf("Entry count: %s\n", responseItem.getEntryCount());
        System.out.printf(
            "Input URI: %s\n", responseItem.getInputConfig().getGcsSource().getInputUri());
      }
    }
  }
}

Node.js

Antes de testar esta amostra, siga as instruções de configuração para Node.js no Guia de início rápido do Translation: como usar bibliotecas de cliente. Saiba mais na documentação de referência da API Translation para Node.js.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function listGlossaries() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  try {
    // Run request
    const [response] = await translationClient.listGlossaries(request);

    for (const glossary of response) {
      console.log(`Name: ${glossary.name}`);
      console.log(`Entry count: ${glossary.entryCount}`);
      console.log(`Input uri: ${glossary.inputConfig.gcsSource.inputUri}`);
      for (const languageCode of glossary.languageCodesSet.languageCodes) {
        console.log(`Language code: ${languageCode}`);
      }
    }
  } catch (error) {
    console.error(error.details);
  }
}

listGlossaries();

PHP

Antes de testar esta amostra, siga as instruções de configuração para PHP no Guia de início rápido do Translation: como usar bibliotecas de cliente. Saiba mais na documentação de referência da API Translation para PHP.

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    'us-central1'
);

try {
    // Iterate through all elements
    $pagedResponse = $translationServiceClient->listGlossaries($formattedParent);
    foreach ($pagedResponse->iterateAllElements() as $responseItem) {
        printf('Glossary name: %s' . PHP_EOL, $responseItem->getName());
        printf('Entry count: %s' . PHP_EOL, $responseItem->getEntryCount());
        printf(
            'Input URI: %s' . PHP_EOL,
            $responseItem->getInputConfig()
                ->getGcsSource()
                ->getInputUri()
        );
    }
} finally {
    $translationServiceClient->close();
}

Python

Antes de testar esta amostra, siga as instruções de configuração para Python no Guia de início rápido do Translation: como usar bibliotecas de cliente. Saiba mais na documentação de referência da API Translation para Python.

from google.cloud import translate

def list_glossaries(project_id="YOUR_PROJECT_ID"):
    """List Glossaries."""

    client = translate.TranslationServiceClient()

    location = "us-central1"

    parent = f"projects/{project_id}/locations/{location}"

    # Iterate over all results
    for glossary in client.list_glossaries(parent=parent):
        print("Name: {}".format(glossary.name))
        print("Entry count: {}".format(glossary.entry_count))
        print("Input uri: {}".format(glossary.input_config.gcs_source.input_uri))

        # Note: You can create a glossary using one of two modes:
        # language_code_set or language_pair. When listing the information for
        # a glossary, you can only get information for the mode you used
        # when creating the glossary.
        for language_code in glossary.language_codes_set.language_codes:
            print("Language code: {}".format(language_code))

Ruby

Antes de testar esta amostra, siga as instruções de configuração para Ruby no Guia de início rápido do Translation: como usar bibliotecas de cliente. Saiba mais na documentação de referência da API Translation para Ruby.

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id

responses = client.list_glossaries parent: parent

responses.each do |response|
  puts "Glossary name: #{response.name}"
  puts "Entry count: #{response.entry_count}"
  puts "Input URI: #{response.input_config.gcs_source.input_uri}"
end