发现支持的语言(高级版)

使用 Cloud Translation API 列出 NMT 模型支持的语言。如需查看 AutoML Translation 支持的语言对,请参阅自定义模型的语言支持

准备工作

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

列出支持的语言

REST

如需获取所有支持的语言列表,请向 https://translation.googleapis.com/v3/projects/project-number-or-id/locations/location/supportedLanguages 网址发出 GET 请求。下面显示了使用 curl 和 PowerShell 的 GET 请求的示例。该示例针对通过 Google Cloud CLI 为项目设置的服务账号使用访问令牌。如需了解有关安装 Google Cloud CLI、使用服务账号设置项目以及获取访问令牌的说明,请参阅设置页面。

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

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

HTTP 方法和网址:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/global/supportedLanguages

如需发送您的请求,请展开以下选项之一:

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

{
  "languages": [
     "languageCode": "af",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "ar",
      "supportSource": true,
      "supportTarget": true
    },
    ....
    {
      "languageCode": "zu",
      "supportSource": true,
      "supportTarget": true
    }
   ]
}

该列表按照语言代码的字母顺序排列。此查询会返回受支持语言的 ISO-639 语言代码。一些语言代码还包含国家/地区代码(如 zh-CN 或 zh-TW)。例如:

   {
      "languageCode": "zh-TW",
      "supportSource": true,
      "supportTarget": true
    },

Go

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

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

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	"cloud.google.com/go/translate/apiv3/translatepb"
)

// getSupportedLanguages gets a list of supported language codes.
func getSupportedLanguages(w io.Writer, projectID string) error {
	// projectID := "my-project-id"

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

	req := &translatepb.GetSupportedLanguagesRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
	}

	resp, err := client.GetSupportedLanguages(ctx, req)
	if err != nil {
		return fmt.Errorf("GetSupportedLanguages: %w", err)
	}

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetSupportedLanguages {

  public static void getSupportedLanguages() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    getSupportedLanguages(projectId);
  }

  // Getting a list of supported language codes
  public static void getSupportedLanguages(String projectId) throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "global");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder().setParent(parent.toString()).build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
      }
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  // Get supported languages
  const [response] = await translationClient.getSupportedLanguages(request);

  for (const language of response.languages) {
    // Supported language code, generally consisting of its ISO 639-1 identifier, for
    // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
    // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
    console.log(`Language - Language Code: ${language.languageCode}`);
    // Human readable name of the language localized in the display language specified
    // in the request.
    console.log(`Language - Display Name: ${language.displayName}`);
    // Can be used as source language.
    console.log(`Language - Support Source: ${language.supportSource}`);
    // Can be used as target language.
    console.log(`Language - Support Target: ${language.supportTarget}`);
  }
}

getSupportedLanguages();

Python

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

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

from google.cloud import translate


def get_supported_languages(
    project_id: str = "YOUR_PROJECT_ID",
) -> translate.SupportedLanguages:
    """Getting a list of supported language codes.

    Args:
        project_id: The GCP project ID.

    Returns:
        A list of supported language codes.
    """
    client = translate.TranslationServiceClient()

    parent = f"projects/{project_id}"

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.get_supported_languages(parent=parent)

    # List language codes of supported languages.
    print("Supported Languages:")
    for language in response.languages:
        print(f"Language Code: {language.language_code}")

    return response

其他语言

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

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

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

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

REST

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

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

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

HTTP 方法和网址:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/global/supportedLanguages?display_language_code=sq

如需发送您的请求,请展开以下选项之一:

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

{
  "languages": [{
      "languageCode": "af",
      "displayName": "Afrikanisht",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "displayName": "Amarikisht",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "en",
      "displayName": "Anglisht",
      "supportSource": true,
      "supportTarget": true
    },
    ...{
      "languageCode": "zu",
      "displayName": "Zulu",
      "supportSource": true,
      "supportTarget": true
    }

	]
}

在这种情况下,查询会返回与上文相同的语言代码,以及 name 字符串,该字符串提供了使用目标语言写出的语言的名称。在此示例中,该语言为阿尔巴尼亚语 (sq)。

Go

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

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

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	"cloud.google.com/go/translate/apiv3/translatepb"
)

// getSupportedLanguagesForTarget gets a list of supported language codes with target language names.
func getSupportedLanguagesForTarget(w io.Writer, projectID string, languageCode string) error {
	// projectID := "my-project-id"
	// languageCode := "is"

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

	req := &translatepb.GetSupportedLanguagesRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/global", projectID),
		DisplayLanguageCode: languageCode,
	}

	resp, err := client.GetSupportedLanguages(ctx, req)
	if err != nil {
		return fmt.Errorf("GetSupportedLanguages: %w", err)
	}

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
		fmt.Fprintf(w, "Display name: %v\n", language.GetDisplayName())
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetSupportedLanguagesForTarget {

  public static void getSupportedLanguagesForTarget() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String languageCode = "your-language-code";
    getSupportedLanguagesForTarget(projectId, languageCode);
  }

  // Listing supported languages with target language name
  public static void getSupportedLanguagesForTarget(String projectId, String languageCode)
      throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "global");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder()
              .setParent(parent.toString())
              .setDisplayLanguageCode(languageCode)
              .build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
        System.out.printf("Display Name: %s\n", language.getDisplayName());
      }
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    displayLanguageCode: 'en',
  };

  // Get supported languages
  const [response] = await translationClient.getSupportedLanguages(request);

  for (const language of response.languages) {
    // Supported language code, generally consisting of its ISO 639-1 identifier, for
    // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
    // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
    console.log(`Language - Language Code: ${language.languageCode}`);
    // Human readable name of the language localized in the display language specified
    // in the request.
    console.log(`Language - Display Name: ${language.displayName}`);
    // Can be used as source language.
    console.log(`Language - Support Source: ${language.supportSource}`);
    // Can be used as target language.
    console.log(`Language - Support Target: ${language.supportTarget}`);
  }
}

getSupportedLanguages();

Python

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

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

from google.cloud import translate


def get_supported_languages_with_target(
    project_id: str = "YOUR_PROJECT_ID",
) -> translate.SupportedLanguages:
    """Listing supported languages with target language name.

    Args:
        project_id: Your Google Cloud project ID.

    Returns:
        Supported languages.
    """
    client = translate.TranslationServiceClient()

    location = "global"

    parent = f"projects/{project_id}/locations/{location}"

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.get_supported_languages(
        display_language_code="is", parent=parent  # target language code
    )
    # List language codes of supported languages
    for language in response.languages:
        print(f"Language Code: {language.language_code}")
        print(f"Display Name: {language.display_name}")

    return response

其他语言

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

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

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

其他资源

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