Traducir texto

En este ejemplo se muestra cómo usar la API Google Cloud Translation para traducir texto de un idioma a otro. El código muestra cómo crear un cliente, definir el idioma de destino y traducir una cadena de texto determinada. Se incluye la gestión de errores para controlar posibles problemas, como códigos de idioma no válidos y errores de la API. La función devuelve el texto traducido o un error si la traducción falla. Para usar este código, deberás configurar la autenticación con la API Google Cloud Translation y tener las credenciales necesarias configuradas en tu entorno. No olvides sustituirlo por el texto que quieras traducir.

Investigar más

Para obtener documentación detallada que incluya este código de muestra, consulta lo siguiente:

Código de ejemplo

Go

Antes de probar este ejemplo, sigue las Go instrucciones de configuración de la guía de inicio rápido de Cloud Translation con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go Cloud Translation.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

// translateText translates the given text into the specified targetLanguage. sourceLanguage
// is optional. If empty, the API will attempt to detect the source language automatically.
// targetLanguage and sourceLanguage should follow ISO 639 language code of the input text
// (e.g., 'fr' for French)
//
// Find a list of supported languages and codes here:
// https://cloud.google.com/translate/docs/languages#nmt
func translateText(w io.Writer, targetLanguage, sourceLanguage, text string) error {
	ctx := context.Background()

	// Create new Translate client.
	client, err := translate.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("translate.NewClient error: %w", err)
	}
	defer client.Close()

	// Get required tag by parsing the target language.
	targetLang, err := language.Parse(targetLanguage)
	if err != nil {
		return fmt.Errorf("language.Parse: %w", err)
	}

	options := &translate.Options{}

	if sourceLanguage != "" {
		sourceLang, err := language.Parse(sourceLanguage)
		if err != nil {
			return fmt.Errorf("language.Parse: %w", err)
		}
		options = &translate.Options{
			Source: sourceLang,
		}
	}

	// Find more information about translate function here:
	// https://pkg.go.dev/cloud.google.com/go/translate#Client.Translate
	resp, err := client.Translate(ctx, []string{text}, targetLang, options)
	if err != nil {
		return fmt.Errorf("client.Translate error: %w", err)
	}
	if len(resp) == 0 {
		return fmt.Errorf("client.Translate returned empty response to text: %s", text)
	}

	// Print results to buffer.
	fmt.Fprintf(w, "Input Text: %s\n", resp[0].Text)
	fmt.Fprintf(w, "Translated Test: %s\n", text)

	return nil
}

Java

Antes de probar este ejemplo, sigue las Java instrucciones de configuración de la guía de inicio rápido de Cloud Translation con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Java Cloud Translation.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

Translation translation = translate.translate("¡Hola Mundo!");
System.out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());

Node.js

Antes de probar este ejemplo, sigue las Node.js instrucciones de configuración de la guía de inicio rápido de Cloud Translation con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js Cloud Translation.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate').v2;

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';

async function translateText() {
  // Translates the text into the target language. "text" can be a string for
  // translating a single piece of text, or an array of strings for translating
  // multiple texts.
  let [translations] = await translate.translate(text, target);
  translations = Array.isArray(translations) ? translations : [translations];
  console.log('Translations:');
  translations.forEach((translation, i) => {
    console.log(`${text[i]} => (${target}) ${translation}`);
  });
}

translateText();

PHP

Antes de probar este ejemplo, sigue las PHP instrucciones de configuración de la guía de inicio rápido de Cloud Translation con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API PHP Cloud Translation.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

use Google\Cloud\Translate\TranslateClient;

/**
 * @param string $text The text to translate.
 * @param string $targetLanguage Language to translate to.
 */
function translate(string $text, string $targetLanguage): void
{
    /** Uncomment and populate these variables in your code */
    // $text = 'The text to translate.';
    // $targetLanguage = 'ja';  // Language to translate to

    $translate = new TranslateClient();
    $result = $translate->translate($text, [
        'target' => $targetLanguage,
    ]);
    print("Source language: $result[source]\n");
    print("Translation: $result[text]\n");
}

Python

Antes de probar este ejemplo, sigue las Python instrucciones de configuración de la guía de inicio rápido de Cloud Translation con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python Cloud Translation.

Para autenticarte en Cloud Translation, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

def translate_text(
    text: str | bytes | list[str] = "¡Hola amigos y amigas!",
    target_language: str = "en",
    source_language: str | None = None,
) -> dict:
    """Translates a given text into the specified target language.

    Find a list of supported languages and codes here:
    https://cloud.google.com/translate/docs/languages#nmt

    Args:
        text: The text to translate. Can be a string, bytes or a list of strings.
              If bytes, it will be decoded as UTF-8.
        target_language: The ISO 639 language code to translate the text into
                         (e.g., 'en' for English, 'es' for Spanish).
        source_language: Optional. The ISO 639 language code of the input text
                         (e.g., 'fr' for French). If None, the API will attempt
                         to detect the source language automatically.

    Returns:
        A dictionary containing the translation results.
    """

    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, bytes):
        text = [text.decode("utf-8")]

    if isinstance(text, str):
        text = [text]

    # If a string is supplied, a single dictionary will be returned.
    # In case a list of strings is supplied, this method
    # will return a list of dictionaries.

    # Find more information about translate function here:
    # https://cloud.google.com/python/docs/reference/translate/latest/google.cloud.translate_v2.client.Client#google_cloud_translate_v2_client_Client_translate
    results = translate_client.translate(
        values=text,
        target_language=target_language,
        source_language=source_language
    )

    for result in results:
        if "detectedSourceLanguage" in result:
            print(f"Detected source language: {result['detectedSourceLanguage']}")

        print(f"Input text: {result['input']}")
        print(f"Translated text: {result['translatedText']}")
        print()

    return results

Siguientes pasos

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