Obtén idiomas compatibles para los idiomas objetivo (edición Advanced)

Recupera una lista de los códigos de idioma compatibles con los nombres de los idiomas objetivo.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración para Go que encontrarás en la guía de inicio rápido de Cloud Translation sobre las bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Go.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	"cloud.google.com/go/translate/apiv3/translatepb"
)

// getSupportedLanguagesForTarget gets a list of supported language codes with target language names.
func getSupportedLanguagesForTarget(w io.Writer, projectID string, languageCode string) error {
	// projectID := "my-project-id"
	// languageCode := "is"

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

	req := &translatepb.GetSupportedLanguagesRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/global", projectID),
		DisplayLanguageCode: languageCode,
	}

	resp, err := client.GetSupportedLanguages(ctx, req)
	if err != nil {
		return fmt.Errorf("GetSupportedLanguages: %w", err)
	}

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
		fmt.Fprintf(w, "Display name: %v\n", language.GetDisplayName())
	}

	return nil
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java que encontrarás en la guía de inicio rápido de Cloud Translation sobre las bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Java.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetSupportedLanguagesForTarget {

  public static void getSupportedLanguagesForTarget() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String languageCode = "your-language-code";
    getSupportedLanguagesForTarget(projectId, languageCode);
  }

  // Listing supported languages with target language name
  public static void getSupportedLanguagesForTarget(String projectId, String languageCode)
      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, "global");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder()
              .setParent(parent.toString())
              .setDisplayLanguageCode(languageCode)
              .build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
        System.out.printf("Display Name: %s\n", language.getDisplayName());
      }
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js que encontrarás en la guía de inicio rápido de Cloud Translation sobre las bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Node.js.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * 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 getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    displayLanguageCode: 'en',
  };

  // Get supported languages
  const [response] = await translationClient.getSupportedLanguages(request);

  for (const language of response.languages) {
    // Supported language code, generally consisting of its ISO 639-1 identifier, for
    // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
    // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
    console.log(`Language - Language Code: ${language.languageCode}`);
    // Human readable name of the language localized in the display language specified
    // in the request.
    console.log(`Language - Display Name: ${language.displayName}`);
    // Can be used as source language.
    console.log(`Language - Support Source: ${language.supportSource}`);
    // Can be used as target language.
    console.log(`Language - Support Target: ${language.supportTarget}`);
  }
}

getSupportedLanguages();

PHP

Antes de probar este ejemplo, sigue las instrucciones de configuración para PHP que encontrarás en la guía de inicio rápido de Cloud Translation sobre las bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage PHP.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\GetSupportedLanguagesRequest;

/**
 * @param string $projectId     Your Google Cloud project ID.
 * @param string $languageCode  Languages to list that are supported by this language code.
 */
function v3_get_supported_languages_for_target(string $languageCode, string $projectId): void
{
    $translationServiceClient = new TranslationServiceClient();

    $formattedParent = $translationServiceClient->locationName($projectId, 'global');

    try {
        $request = (new GetSupportedLanguagesRequest())
            ->setParent($formattedParent)
            ->setDisplayLanguageCode($languageCode);
        $response = $translationServiceClient->getSupportedLanguages($request);
        // List language codes of supported languages
        foreach ($response->getLanguages() as $language) {
            printf('Language Code: %s' . PHP_EOL, $language->getLanguageCode());
            printf('Display Name: %s' . PHP_EOL, $language->getDisplayName());
        }
    } finally {
        $translationServiceClient->close();
    }
}

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración para Python que encontrarás en la guía de inicio rápido de Cloud Translation sobre las bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Python.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

from google.cloud import translate

def get_supported_languages_with_target(
    project_id: str = "YOUR_PROJECT_ID",
) -> translate.SupportedLanguages:
    """Listing supported languages with target language name.

    Args:
        project_id: Your Google Cloud project ID.

    Returns:
        Supported languages.
    """
    client = translate.TranslationServiceClient()

    location = "global"

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

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.get_supported_languages(
        display_language_code="is", parent=parent  # target language code
    )
    # List language codes of supported languages
    for language in response.languages:
        print(f"Language Code: {language.language_code}")
        print(f"Display Name: {language.display_name}")

    return response

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.