翻译文本(基本版)

本文档介绍了如何使用 Cloud Translation 基本版 (v2) 翻译文本。

输入文本可以是纯文本或 HTML。Cloud Translation 基本版不会翻译输入文本中的任何 HTML 标记,只会翻译出现在标记之间的文本。由于源语言和目标语言之间存在差异,输出会尽可能地保留(未翻译的)HTML 标记,并将翻译的文本置于标记之间。 由于翻译中的词序更改,输出中 HTML 标记的顺序可能与输入文本中的顺序不同。

准备工作

在开始使用 Cloud Translation API 之前,您必须具有启用了 Cloud Translation API 的项目,并且必须具有适当的凭据。您还可以安装常用编程语言的客户端库,以便调用 API。如需了解详情,请参阅设置页面。

翻译文本

本部分介绍了从 https://translation.googleapis.com/language/translate/v2 端点请求翻译的一些方法。

翻译输入字符串

REST

要翻译文本,请发出 POST 请求,并在请求正文中提供 JSON,以标识要翻译的语言 (target) 以及要翻译的文本 (q)。您可以通过添加多个 q 字段或 q 字段值列表来提供多个要翻译的文本片段,所提供的文本段不能超过 128 个。您可以使用相应的 ISO-639 代码来指定目标语言。

下面显示了使用 curl 或 PowerShell 的 POST 请求的示例。该示例使用通过 Google Cloud Google Cloud CLI 为项目设置的服务账号的访问令牌。如需了解有关安装 Google Cloud CLI、使用服务账号设置项目以及获取访问令牌的说明,请参阅设置页面。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID

HTTP 方法和网址:

POST https://translation.googleapis.com/language/translate/v2

请求 JSON 正文:

{
  "q": ["Hello world", "My name is Jeff"],
  "target": "de"
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_NUMBER_OR_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://translation.googleapis.com/language/translate/v2"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_NUMBER_OR_ID" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/language/translate/v2" | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应:

{
  "data": {
    "translations": [
      {
        "translatedText": "Hallo Welt",
        "detectedSourceLanguage": "en"
      },
      {
        "translatedText": "Mein Name ist Jeff",
        "detectedSourceLanguage": "en"
      }
    ]
  }
}

translations 数组包含两个 translatedText 字段,其中译文以请求的 target 语言(de:德语)提供。译文的排列顺序与相应源数组在请求中的顺序相同。

Go

试用此示例之前,请按照 Cloud Translation 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Cloud Translation Go API 参考文档

如需向 Cloud Translation 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

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

试用此示例之前,请按照 Cloud Translation 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Cloud Translation Java API 参考文档

如需向 Cloud Translation 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

// 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

试用此示例之前,请按照 Cloud Translation 快速入门:使用客户端库中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Cloud Translation Node.js API 参考文档

如需向 Cloud Translation 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

// 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();

Python

试用此示例之前,请按照 Cloud Translation 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Cloud Translation Python API 参考文档

如需向 Cloud Translation 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证

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

其他语言

C#:请按照客户端库页面上的 C# 设置说明操作,然后访问 .NET 版 Cloud Translation 参考文档

PHP:请按照客户端库页面上的 PHP 设置说明操作,然后访问 PHP 版 Cloud Translation 参考文档

Ruby:请按照客户端库页面上的 Ruby 设置说明操作,然后访问 Ruby 版 Cloud Translation 参考文档

模型参数

当您向 Cloud Translation 基本版发出翻译请求时,系统将使用 Google 神经机器翻译 (NMT) 模型翻译您的文本。您不能使用任何其他模型。如需使用 AutoML 模型翻译文本,请使用 Cloud Translation 高级版

自行试用

如果您是 Google Cloud 新手,请创建一个账号来评估 Cloud Translation 在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。

免费试用 Cloud Translation

其他资源

  • 如需有关解决常见问题或错误的帮助,请参阅问题排查页面。