Traduzir strings (edição Basic)

Traduza strings usando a Cloud Translation - Basic (v2).

Exemplo de código

Go

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

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"

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

func translateTextWithModel(targetLanguage, text, model string) (string, error) {
	// targetLanguage := "ja"
	// text := "The Go Gopher is cute"
	// model := "nmt"

	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return "", fmt.Errorf("language.Parse: %w", err)
	}

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

	resp, err := client.Translate(ctx, []string{text}, lang, &translate.Options{
		Model: model, // Either "nmt" or "base".
	})
	if err != nil {
		return "", fmt.Errorf("Translate: %w", err)
	}
	if len(resp) == 0 {
		return "", nil
	}
	return resp[0].Text, nil
}

Java

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

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Translation translation =
    translate.translate(
        "Hola Mundo!",
        Translate.TranslateOption.sourceLanguage("es"),
        Translate.TranslateOption.targetLanguage("de"),
        // Use "base" for standard edition, "nmt" for the premium model.
        Translate.TranslateOption.model("nmt"));

System.out.printf("TranslatedText:\nText: %s\n", translation.getTranslatedText());

Node.js

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

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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';
// const model = 'The model to use, e.g. nmt';

async function translateTextWithModel() {
  const options = {
    // The target language, e.g. "ru"
    to: target,
    // Make sure your project is on the allow list.
    // Possible values are "base" and "nmt"
    model: model,
  };

  // 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, options);
  translations = Array.isArray(translations) ? translations : [translations];
  console.log('Translations:');
  translations.forEach((translation, i) => {
    console.log(`${text[i]} => (${target}) ${translation}`);
  });
}

translateTextWithModel();

PHP

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

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

use Google\Cloud\Translate\TranslateClient;

/**
 * @param string $text The text to translate.
 * @param string $targetLanguage Language to translate to.
 */
function translate_with_model(string $text, string $targetLanguage): void
{
    $model = 'nmt';  // "base" for standard edition, "nmt" for premium
    $translate = new TranslateClient();
    $result = $translate->translate($text, [
        'target' => $targetLanguage,
        'model' => $model,
    ]);
    print("Source language: $result[source]\n");
    print("Translation: $result[text]\n");
    print("Model: $result[model]\n");
}

Python

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

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

def translate_text_with_model(target: str, text: str, model: str = "nmt") -> dict:
    """Translates text into the target language.

    Make sure your project is allowlisted.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

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

    # Text can also be a sequence of strings, in which case this method
    # will return a sequence of results for each text.
    result = translate_client.translate(text, target_language=target, model=model)

    print("Text: {}".format(result["input"]))
    print("Translation: {}".format(result["translatedText"]))
    print("Detected source language: {}".format(result["detectedSourceLanguage"]))

    return result

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte a pesquisa de exemplos de código do Google Cloud.