发现支持的语言(基本版)

本文档介绍了如何使用 Cloud Translation API (v2) 列出支持的语言。

准备工作

在开始使用 Cloud Translation API 之前,您必须有一个启用了 Cloud Translation API 的项目,以及相应的凭据。您还可以安装常用编程语言的客户端库,以便调用 API。

如需了解详情,请参阅设置页面。

发送支持的语言请求

您可以通过使用以下格式的网址发送 HTTP 请求来发现此 API 支持的语言

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

获取支持的语言列表

REST 和命令行

如需获取所有支持的语言列表,请向 https://translation.googleapis.com/language/translate/v2/languages 端点发出 GET 请求。下面显示了使用 curl 和 PowerShell 的 GET 请求的示例。本示例针对通过 Cloud SDK 为项目设置的服务帐号使用访问令牌。如需了解有关安装 Cloud SDK、使用服务帐号设置项目以及获取访问令牌的说明,请参阅设置页面。

HTTP 方法和网址:

GET https://translation.googleapis.com/language/translate/v2/languages

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

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/language/translate/v2/languages

PowerShell

执行以下命令:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://translation.googleapis.com/language/translate/v2/languages " | Select-Object -Expand Content

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

{
  "languages": [
    {
      "language": "en"
    },
    {
      "language": "fr"
    },
    {
      "language": "zh-CN"
    }
  ]
}

此查询会返回受支持语言的 ISO-639-1 语言代码。一些语言代码还包含国家/地区代码(如 zh-CN 或 zh-TW)。该列表按照语言代码的字母顺序排列。由于空间限制,上述示例已被缩短。

Go

import (
	"context"
	"fmt"
	"io"

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

func listSupportedLanguages(w io.Writer, targetLanguage string) error {
	// targetLanguage := "th"
	ctx := context.Background()

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

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

	langs, err := client.SupportedLanguages(ctx, lang)
	if err != nil {
		return fmt.Errorf("SupportedLanguages: %v", err)
	}

	for _, lang := range langs {
		fmt.Fprintf(w, "%q: %s\n", lang.Tag, lang.Name)
	}

	return nil
}

Java

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

List<Language> languages = translate.listSupportedLanguages();

for (Language language : languages) {
  System.out.printf("Name: %s, Code: %s\n", language.getName(), language.getCode());
}

Node.js

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

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

async function listLanguages() {
  // Lists available translation language with their names in English (the default).
  const [languages] = await translate.getLanguages();

  console.log('Languages:');
  languages.forEach(language => console.log(language));
}

listLanguages();

Python

def list_languages():
    """Lists all available languages."""
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    results = translate_client.get_languages()

    for language in results:
        print(u"{name} ({language})".format(**language))

使用目标语言列出支持的语言

REST 和命令行

下面是返回受支持语言列表的另一个示例。返回的语言名称是用指定的目标语言编写的。返回的列表按照目标语言的字母顺序排列。

如需列出目标语言支持的语言,请发出 POST 请求并在请求正文中提供用于标识目标语言的 JSON 代码。下面显示了使用 curl 或 PowerShell 的 POST 请求的示例。

HTTP 方法和网址:

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

请求 JSON 正文:

{
    "target": "zh-TW"
}

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

curl

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

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

PowerShell

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

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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

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

{
  "data": {
    "languages": [
      {
        "language": "zh-CN",
        "name": "中文(簡體)"
      },
      {
        "language": "fr",
        "name": "法文"
      },
      {
        "language": "en",
        "name": "英文"
      }
    ]
  }
}

在这种情况下,查询会返回与上文相同的语言代码,以及 name 字符串,该字符串提供了使用目标语言 zh-TW 写出的语言的名称。由于空间限制,上述示例已被缩短。

Go

import (
	"context"
	"fmt"
	"io"

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

func listSupportedLanguages(w io.Writer, targetLanguage string) error {
	// targetLanguage := "th"
	ctx := context.Background()

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

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

	langs, err := client.SupportedLanguages(ctx, lang)
	if err != nil {
		return fmt.Errorf("SupportedLanguages: %v", err)
	}

	for _, lang := range langs {
		fmt.Fprintf(w, "%q: %s\n", lang.Tag, lang.Name)
	}

	return nil
}

Java

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

List<Language> languages =
    translate.listSupportedLanguages(Translate.LanguageListOption.targetLanguage("es"));

for (Language language : languages) {
  System.out.printf("Name: %s, Code: %s\n", language.getName(), language.getCode());
}

Node.js

// 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 line before running the sample.
 */
// const target = 'The target language for language names, e.g. ru';

async function listLanguagesWithTarget() {
  // Lists available translation language with their names in a target language
  const [languages] = await translate.getLanguages(target);

  console.log('Languages:');
  languages.forEach(language => console.log(language));
}

listLanguagesWithTarget();

Python

def list_languages_with_target(target):
    """Lists all available languages and localizes them to the target language.

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

    results = translate_client.get_languages(target_language=target)

    for language in results:
        print(u"{name} ({language})".format(**language))