翻译文本

本文档介绍了如何使用 Cloud Translation API 翻译文本。

翻译文本

本部分演示了向 https://translation.googleapis.com/language/translate/v2 端点发送翻译请求的几种方法。

翻译输入字符串

协议

要检测某些文本的语言,请发出 POST 请求,并在请求正文中提供 JSON,以标识源翻译语言 (source)、目标翻译语言 (target) 以及要翻译的文本 (q)。您可以提供多个要翻译的文本字符串,只需在您的 JSON 中加入多个 q 参数即可。源语言和目标语言可以使用相应的 iso-639-1 代码进行标识。

以下示例显示了一个使用 curl 发出的 POST 请求。该示例对服务帐号(设置用于使用 Google Cloud Platform Cloud SDK 的项目)使用了访问令牌。有关安装 Cloud SDK、为项目设置服务帐号以及获取访问令牌的说明,请参阅快速入门

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'q': 'Hello world',
  'q': 'My name is Jeff',
  'target': 'de'
}" "https://translation.googleapis.com/language/translate/v2"

如果请求成功,服务器将返回一个 200 OK HTTP 状态代码以及 JSON 格式的响应:

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

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

C#

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

static void Translate(string text, string targetLanguageCode,
    string sourceLanguageCode)
{
    TranslationClient client = TranslationClient.Create();
    var response = client.TranslateText(text, targetLanguageCode,
        sourceLanguageCode);
    Console.WriteLine(response.TranslatedText);
}

Go

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

func translateText(targetLanguage, text string) (string, error) {
	ctx := context.Background()

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

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

	resp, err := client.Translate(ctx, []string{text}, lang, nil)
	if err != nil {
		return "", err
	}
	return resp[0].Text, nil
}

Java

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

public static void translateText(String sourceText, PrintStream out) {
  Translate translate = createTranslateService();
  Translation translation = translate.translate(sourceText);
  out.printf("Source Text:\n\t%s\n", sourceText);
  out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());
}

Node.js

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

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

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

// 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.
translate
  .translate(text, target)
  .then(results => {
    let translations = results[0];
    translations = Array.isArray(translations)
      ? translations
      : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

use Google\Cloud\Translate\TranslateClient;

// $text = 'The text to translate."
// $targetLanguage = 'ja';  // Which 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

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

"""Translates text into the target language.

Target must be an ISO 639-1 language code.
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
"""
translate_client = translate.Client()

if isinstance(text, six.binary_type):
    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)

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

Ruby

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

# project_id    = "Your Google Cloud project ID"
# text          = "The text you would like to translate"
# language_code = "The ISO 639-1 code of language to translate to, eg. 'en'"

require "google/cloud/translate"

translate   = Google::Cloud::Translate.new project: project_id
translation = translate.translate text, to: language_code

puts "Translated '#{text}' to '#{translation.text.inspect}'"
puts "Original language: #{translation.from} translated to: #{translation.to}"

指定模型

默认情况下,当您向 Cloud Translation API 发起翻译请求时,系统将使用神经机器翻译 (NMT) 模型翻译您的文本。如果 NMT 模型不支持所请求的翻译语言对,系统则会使用基于短语的机器翻译 (PBMT) 模型。

比较模型

NMT 模型可以为较长且较为复杂的内容提供更佳的译文。例如,请考虑下面的请求:

{
  'q': 'So let us begin anew--remembering on both sides that civility is not a
        sign of weakness, and sincerity is always subject to proof. Let us never
        negotiate out of fear. But let us never fear to negotiate.',
  'target': 'de',
}

由于请求中没有指定 model,并且 NMT 模型支持英语和德语这对翻译语言,因此系统使用 nmt 模型翻译该请求。以下是在响应的 translations 字段中返回的内容:

"translatedText": "Fangen wir also von neuem an - auf beiden Seiten erinnern wir
                   uns, daß die Höflichkeit kein Zeichen der Schwäche ist und
                   die Aufrichtigkeit immer unter Beweis gestellt wird. Lasst
                   uns nie aus Furcht verhandeln. Aber lassen Sie uns niemals
                   Angst haben, zu verhandeln.",
"detectedSourceLanguage": "en",
"model": "nmt"

或者,您可以明确要求使用 base (PBMT) 模型翻译文本。

{
  'q': 'So let us begin anew--remembering on both sides that civility is not a
        sign of weakness, and sincerity is always subject to proof. Let us never
        negotiate out of fear. But let us never fear to negotiate.',
  'target': 'de',
  'model': 'base',
}

使用 base 模型时,响应的 translations 字段会返回以下结果,这与使用 nmt 模型时的翻译结果有所不同。

"translatedText": "Lassen Sie uns also neu beginnen - auf beiden Seiten nicht
                   vergessen, dass Zivilität ist kein Zeichen von Schwäche, und
                   Aufrichtigkeit ist immer unter Beweis. Lassen Sie uns nie aus
                   Angst verhandeln. Aber lassen Sie uns nie zu verhandeln
                   fürchten.",
"detectedSourceLanguage": "en",
"model": "base"

使用模型参数

您可以使用 model 查询参数指定使用哪个模型进行翻译。若要使用 PBMT 模型,请指定 base;若要使用 NMT 模型,则请指定 nmt。如果您在请求中指定了 NMT 模型,但 NMT 模型不支持请求的翻译语言对,系统则会使用 PBMT 模型。

以下示例显示了如何在翻译请求中使用 model 参数。

协议

要使用 nmt 模型翻译文本,请将 model 参数加入您的 POST 请求中。

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'q': 'So let us begin anew--remembering on both sides that civility is not a
        sign of weakness, and sincerity is always subject to proof. Let us never
        negotiate out of fear. But let us never fear to negotiate.',
  'target': 'de',
  'model': 'nmt',
}" "https://translation.googleapis.com/language/translate/v2"

如果请求成功,服务器将返回一个 200 OK HTTP 状态代码以及 JSON 格式的响应:

{
  "data": {
    "translations": [
      {
        "translatedText": "Lasst uns also von neuem beginnen - erinnert euch
           auf beiden Seiten, dass Höflichkeit kein Zeichen von Schwäche ist,
           und Aufrichtigkeit immer dem Beweis unterliegt. Lasst uns niemals
           aus Angst verhandeln. Aber lassen Sie uns niemals Angst haben zu
           verhandeln.",
        "detectedSourceLanguage": "en",
        "model": "nmt"
      }
    ]
  }
}

C#

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

static void TranslateWithModel(string text,
    string targetLanguageCode, string sourceLanguageCode,
    TranslationModel model)
{
    TranslationClient client = TranslationClient.Create();
    var response = client.TranslateText(text,
        targetLanguageCode, sourceLanguageCode, model);
    Console.WriteLine("Model: {0}", response.Model);
    Console.WriteLine(response.TranslatedText);
}

Node.js

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

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

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

const options = {
  // The target language, e.g. "ru"
  to: target,
  // Make sure your project is whitelisted.
  // 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.
translate
  .translate(text, options)
  .then(results => {
    let translations = results[0];
    translations = Array.isArray(translations)
      ? translations
      : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Python

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

"""Translates text into the target language.

Make sure your project is whitelisted.

Target must be an ISO 639-1 language code.
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
"""
translate_client = translate.Client()

if isinstance(text, six.binary_type):
    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(u'Text: {}'.format(result['input']))
print(u'Translation: {}'.format(result['translatedText']))
print(u'Detected source language: {}'.format(
    result['detectedSourceLanguage']))

PHP

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

use Google\Cloud\Translate\TranslateClient;

// $text = 'The text to translate.';
// $targetLanguage = 'ja';  // Which language to translate to?
// $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");

Java

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

public static void translateTextWithOptionsAndModel(
    String sourceText,
    String sourceLang,
    String targetLang,
    PrintStream out) {

  Translate translate = createTranslateService();
  TranslateOption srcLang = TranslateOption.sourceLanguage(sourceLang);
  TranslateOption tgtLang = TranslateOption.targetLanguage(targetLang);

  // Use translate `model` parameter with `base` and `nmt` options.
  TranslateOption model = TranslateOption.model("nmt");

  Translation translation = translate.translate(sourceText, srcLang, tgtLang, model);
  out.printf("Source Text:\n\tLang: %s, Text: %s\n", sourceLang, sourceText);
  out.printf("TranslatedText:\n\tLang: %s, Text: %s\n", targetLang,
      translation.getTranslatedText());
}

Ruby

如需详细了解如何安装和创建 Translation API 客户端,请参阅 Translation API 客户端库

# project_id    = "Your Google Cloud project ID"
# text          = "The text you would like to translate"
# language_code = "The ISO 639-1 code of language to translate to, eg. 'en'"

require "google/cloud/translate"

translate   = Google::Cloud::Translate.new project: project_id
translation = translate.translate text, to: language_code, model: "nmt"

puts "Translated '#{text}' to '#{translation.text.inspect}'"
puts "Original language: #{translation.from} translated to: #{translation.to}"

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Cloud Translation API 文档