创建和使用术语表(高级版)

术语表是一种自定义字典,用于确保 Cloud Translation API 以一致的方式对客户特定领域的术语进行翻译。这通常涉及指定如何翻译命名实体。

您可以为以下用例使用术语表:

  • 产品名称:例如,“Google Home”必须翻译为“Google Home”。
  • 有歧义的字词:例如,“bat”一词既可能表示体育用品,也可能表示动物。如果您知道自己正在翻译有关体育的字词,您可能需要使用术语表向 Cloud Translation API 提供“bat”的体育用品译文,而非动物相关译文。
  • 外来词:例如,法语的“bouillabaisse”翻译为英语的“bouillabaisse”。十九世纪,英语借用了法语中的“bouillabaisse”一词。一个说英语的人,如果欠缺法国文化背景知识,可能不知道 bouillabaisse 是一种浓味鱼肉汤。术语表可以替换译文,以便将法语的“bouillabaisse”翻译为英语的“fish stew”。

准备工作

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

所需权限

要使用术语表,您的服务账号需要具备特定于术语表的权限。您可以使用预定义的 IAM 角色(例如 Cloud Translation API Editor (roles/cloudtranslate.editor))之一向服务账号授予角色,或者创建能够授予所需权限的自定义角色。您可以参阅 IAM 权限参考文档,了解所有 Cloud Translation API 权限。Cloud Translation 权限前缀为 cloudtranslate

要创建术语表,您还需要具备读取术语表所在的 Cloud Storage 存储桶内的文件的权限。您可以使用预定义的 IAM 角色之一(例如 Storage Object Viewer (roles/storage.objectViewer))向服务账号授予角色,或者创建可授予读取对象权限的自定义角色

如需了解如何向角色添加账号,请参阅授予、更改、撤消对资源的访问权限

创建术语表

术语表中的术语可以是单个词条(单词)或短语(通常少于五个单词)。要使用术语表,您需要执行以下主要步骤:

  1. 创建术语表文件
  2. 使用我们的 Cloud Translation API 创建术语表资源
  3. 请求翻译时指定要使用的术语表

一个项目可以有多个术语表。您可以获取可用术语表的列表,还可以删除不再需要的术语表

无效搜索字词

Cloud Translation 会忽略术语表中包含的一些术语:这些术语称为无效搜索字词。在翻译无效搜索字词时,Cloud Translation 会忽略任何匹配的术语表条目。如需查看所有无效搜索字词的列表,请参阅术语表无效搜索字词

创建术语表文件

从根本上说,术语表是一个文本文件,其中每一行包含对应术语的多种语言版本翻译。Cloud Translation API 既支持使用单向术语表指定一对源语言和目标语言所需的翻译,也支持使用等效术语集确定多种语言版本的等效术语。

一个术语表输入文件中的术语总数(包括所有语言的所有术语)不能超过 10485760 个 UTF-8 字节。术语表中的任何一个术语都必须小于 1024 个 UTF-8 字节。长度超过 1024 个字节的术语会被忽略。

默认情况下,术语表匹配项区分大小写。应用术语表时,您可以忽略所有条目的大小写。如果混合使用区分大小写的术语和不区分大小写的术语,请使用默认行为;如果术语不区分大小写,请在术语表中添加这两种形式。

单向术语表

Cloud Translation API 接受 TSV、CSV 或 TMX 文件。

TSV 和 CSV

对于制表符分隔值 (TSV) 和逗号分隔值 (CSV),每一行都包含一对由制表符 (\t) 或逗号 (,) 分隔的字词。第一列包含源语言字词,第二列包含目标语言字词,如以下示例所示:

单向术语表

TMX 格式

TMX 格式是一种用于提供源文本和目标译文的标准 XML 格式。Cloud Translation API 支持采用 TMX 1.4 版格式的输入文件。此示例说明了所需的结构:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE tmx SYSTEM "tmx14.dtd">
<tmx version="1.4">
  <header segtype="sentence" o-tmf="UTF-8"
  adminlang="en" srclang="en" datatype="PlainText"/>
  <body>
    <tu>
      <tuv xml:lang="en">
        <seg>account</seg>
      </tuv>
      <tuv xml:lang="es">
        <seg>cuenta</seg>
      </tuv>
    </tu>
    <tu>
      <tuv xml:lang="en">
        <seg>directions</seg>
      </tuv>
      <tuv xml:lang="es">
        <seg>indicaciones</seg>
      </tuv>
    </tu>
  </body>
</tmx>

在格式正确的 TMX 文件中,<header> 元素必须使用 srclang 特性标识源语言,并且每个 <tuv> 元素都必须使用 xml:lang 特性标识所含文本的语言。您可以使用 ISO-639 代码来标识源语言和目标语言。

所有 <tu> 元素必须包含一对具有相同源语言和目标语言的 <tuv> 元素。如果一个 <tu> 元素包含两个以上的 <tuv> 元素,则 Cloud Translation API 只会处理与源语言和目标语言匹配的第一对 <tuv> 并忽略其余 <tuv> 元素。 如果一个 <tu> 元素没有匹配的 <tuv> 元素对,则 Cloud Translation API 会跳过无效的 <tu> 元素。

Cloud Translation API 在处理 <seg> 元素之前,会先剥离其周围的标记。如果一个 <tuv> 元素包含多个 <seg> 元素,则 Cloud Translation API 会将其中的文本连接成一个元素,并在它们之间留一个空格。

如果文件包含上文没有提及的 XML 标记,则 Cloud Translation API 将忽略这些标记。

如果文件不符合正确的 XML 和 TMX 格式,例如缺少结束标记或 <tmx> 元素,则 Cloud Translation API 将取消处理。如果 Cloud Translation API 跳过 1024 个以上无效的 <tu> 元素,那么系统也会取消处理。

等效术语集 (CSV)

对于等效术语集,Cloud Translation API 仅接受 CSV 格式的文件。如需定义等效术语集,您可以创建一个多列 CSV 文件,其中每一行列出一个术语表术语的多种语言版本翻译。

此文件中的第一行是标题行,其中使用 ISO-639BCP-47 语言代码标识每一列对应的语言。您还可以选择添加词性 (pos) 列和说明 (description) 列。该算法目前不使用 pos 信息,并且不会验证特定的 pos 值。

后续各行包含标题中所标识语言版本的等效术语表术语。如果该术语仅提供了部分语言版本,则可以将某些列留空。

等效术语集

创建术语表资源

确定等效术语表术语以后,您可以通过创建术语表资源,使术语表文件可用于 Cloud Translation API。

单向术语表

创建单向术语表时,必须通过指定源语言 (source_language_code) 和目标语言 (target_language_code) 来指示语言对 (language_pair)。以下示例使用的是 REST API 和命令行,但您也可以使用客户端库创建单向术语表。

REST

创建新的术语表时,需要提供术语表 ID(资源名称)。 例如:
projects/my-project/locations/us-central1/glossaries/my-en-to-ru-glossary
其中 my-project 是 PROJECT_NUMBER_OR_ID,my-en-ru-glossary 是您提供的 glossary-id。

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID
  • glossary-id:您的术语表 ID,例如 my_en_ru_glossary
  • bucket-name:您的术语表文件所在的存储桶的名称
  • glossary-filename:术语表的文件名

HTTP 方法和网址:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries

请求 JSON 正文:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id",
  "languagePair": {
    "sourceLanguageCode": "en",
    "targetLanguageCode": "ru"
    },
  "inputConfig": {
    "gcsSource": {
      "inputUri": "gs://bucket-name/glossary-filename"
    }
  }
}

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

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

{
  "name": "projects/project-number/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3beta1.CreateGlossaryMetadata",
    "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
    "state": "RUNNING",
    "submitTime": "2019-11-19T19:05:10.650047636Z"
  }
}

等效术语集术语表

在等效术语集中确定术语表术语以后,请通过创建术语表资源,使术语表文件可用于 Cloud Translation API。

REST

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID
  • glossary-id:您的术语表 ID
  • bucket-name:您的术语表文件所在的存储桶的名称
  • glossary-filename:术语表的文件名

HTTP 方法和网址:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries

请求 JSON 正文:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id",
  "languageCodesSet": {
    "languageCodes": ["en", "en-GB", "ru", "fr", "pt-BR", "pt-PT", "es"]
  },
  "inputConfig": {
    "gcsSource": {
"inputUri": "gs://bucket-name/glossary-file-name"
    }
  }
}

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

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

{
  "name": "projects/project-number/locations/us-central1/operations/20191103-09061569945989-5d937985-0000-21ac-816d-f4f5e80782d4",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3beta1.CreateGlossaryMetadata",
    "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
    "state": "RUNNING",
    "submitTime": "2019-11-03T16:06:29.134496675Z"
  }
}

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

// createGlossary creates a glossary to use for other operations.
func createGlossary(w io.Writer, projectID string, location string, glossaryID string, glossaryInputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "my-glossary-display-name"
	// glossaryInputURI := "gs://cloud-samples-data/translation/glossary.csv"

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

	req := &translatepb.CreateGlossaryRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Glossary: &translatepb.Glossary{
			Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
			Languages: &translatepb.Glossary_LanguageCodesSet_{
				LanguageCodesSet: &translatepb.Glossary_LanguageCodesSet{
					LanguageCodes: []string{"en", "ja"},
				},
			},
			InputConfig: &translatepb.GlossaryInputConfig{
				Source: &translatepb.GlossaryInputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{
						InputUri: glossaryInputURI,
					},
				},
			},
		},
	}

	// The CreateGlossary operation is async.
	op, err := client.CreateGlossary(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateGlossary: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

	fmt.Fprintf(w, "Created: %v\n", resp.GetName())
	fmt.Fprintf(w, "Input URI: %v\n", resp.InputConfig.GetGcsSource().GetInputUri())

	return nil
}

Java

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

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

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.translate.v3.CreateGlossaryMetadata;
import com.google.cloud.translate.v3.CreateGlossaryRequest;
import com.google.cloud.translate.v3.GcsSource;
import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.GlossaryInputConfig;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class CreateGlossary {

  public static void createGlossary() throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    List<String> languageCodes = new ArrayList<>();
    languageCodes.add("your-language-code");
    String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt";
    createGlossary(projectId, glossaryId, languageCodes, inputUri);
  }

  // Create a equivalent term sets glossary
  // https://cloud.google.com/translate/docs/advanced/glossary#format-glossary
  public static void createGlossary(
      String projectId, String glossaryId, List<String> languageCodes, String inputUri)
      throws IOException, ExecutionException, InterruptedException {

    // 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)
      String location = "us-central1";
      LocationName parent = LocationName.of(projectId, location);
      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);

      // Supported Languages: https://cloud.google.com/translate/docs/languages
      Glossary.LanguageCodesSet languageCodesSet =
          Glossary.LanguageCodesSet.newBuilder().addAllLanguageCodes(languageCodes).build();

      // Configure the source of the file from a GCS bucket
      GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
      GlossaryInputConfig inputConfig =
          GlossaryInputConfig.newBuilder().setGcsSource(gcsSource).build();

      Glossary glossary =
          Glossary.newBuilder()
              .setName(glossaryName.toString())
              .setLanguageCodesSet(languageCodesSet)
              .setInputConfig(inputConfig)
              .build();

      CreateGlossaryRequest request =
          CreateGlossaryRequest.newBuilder()
              .setParent(parent.toString())
              .setGlossary(glossary)
              .build();

      // Start an asynchronous request
      OperationFuture<Glossary, CreateGlossaryMetadata> future =
          client.createGlossaryAsync(request);

      System.out.println("Waiting for operation to complete...");
      Glossary response = future.get();
      System.out.println("Created Glossary.");
      System.out.printf("Glossary name: %s\n", response.getName());
      System.out.printf("Entry count: %s\n", response.getEntryCount());
      System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri());
    }
  }
}

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';
// const glossaryId = 'your-glossary-display-name';

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

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

async function createGlossary() {
  // Construct glossary
  const glossary = {
    languageCodesSet: {
      languageCodes: ['en', 'es'],
    },
    inputConfig: {
      gcsSource: {
        inputUri: 'gs://cloud-samples-data/translation/glossary.csv',
      },
    },
    name: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };

  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    glossary: glossary,
  };

  // Create glossary using a long-running operation
  const [operation] = await translationClient.createGlossary(request);

  // Wait for the operation to complete
  await operation.promise();

  console.log('Created glossary:');
  console.log(`InputUri ${request.glossary.inputConfig.gcsSource.inputUri}`);
}

createGlossary();

Python

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

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

from google.cloud import translate_v3 as translate

def create_glossary(
    project_id: str = "YOUR_PROJECT_ID",
    input_uri: str = "YOUR_INPUT_URI",
    glossary_id: str = "YOUR_GLOSSARY_ID",
    timeout: int = 180,
) -> translate.Glossary:
    """
    Create a equivalent term sets glossary. Glossary can be words or
    short phrases (usually fewer than five words).
    https://cloud.google.com/translate/docs/advanced/glossary#format-glossary
    """
    client = translate.TranslationServiceClient()

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    source_lang_code = "en"
    target_lang_code = "ja"
    location = "us-central1"  # The location of the glossary

    name = client.glossary_path(project_id, location, glossary_id)
    language_codes_set = translate.types.Glossary.LanguageCodesSet(
        language_codes=[source_lang_code, target_lang_code]
    )

    gcs_source = translate.types.GcsSource(input_uri=input_uri)

    input_config = translate.types.GlossaryInputConfig(gcs_source=gcs_source)

    glossary = translate.types.Glossary(
        name=name, language_codes_set=language_codes_set, input_config=input_config
    )

    parent = f"projects/{project_id}/locations/{location}"
    # glossary is a custom dictionary Translation API uses
    # to translate the domain-specific terminology.
    operation = client.create_glossary(parent=parent, glossary=glossary)

    result = operation.result(timeout)
    print(f"Created: {result.name}")
    print(f"Input Uri: {result.input_config.gcs_source.input_uri}")

    return result

其他语言

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

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

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

操作状态

术语表创建属于一项长时间运行的操作,可能需要大量时间才能完成。您可以轮询此操作的状态以查看它是否已完成,也可以取消此操作。

如需了解详情,请参阅长时间运行的操作

使用术语表

使用术语表翻译文本

在 Cloud Translation 高级版中,您可以明确指定要用于翻译文本的翻译模型。还可以确定为特定领域的术语使用的术语表。

REST

以下示例使用默认 NMT 模型和术语表翻译文本。

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID。
  • glossary-id:您的术语表 ID,例如 my-en-ru-glossary
  • BOOLEAN:匹配是否不区分大小写。默认情况下,此值为 false

HTTP 方法和网址:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:translateText

请求 JSON 正文:

{
  "sourceLanguageCode": "en",
  "targetLanguageCode": "ru",
  "contents": "Dr. Watson, please discard your trash. You've shared unsolicited email with me. Let's talk about spam and importance ranking in a confidential mode.",
  "glossaryConfig": {
    "glossary": "projects/project-number/locations/us-central1/glossaries/glossary-id",
    "ignoreCase": BOOLEAN
  }
}

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

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

{
  "glossaryTranslations": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора. Вы поделились нежелательной электронной почтой со я . Давайте поговорим о спаме и важности рейтинга в конфиденциальном режиме.",
    "glossaryConfig": {
      "glossary": "projects/project-number/locations/us-central1/glossaries/glossary-id",
      "ignoreCase": BOOLEAN
    }
  },
  "translations": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора. Вы поделились нежелательной электронной почтой со мной. Давайте поговорим о спаме и важности рейтинга в конфиденциальном режиме.",
  }
}

translations 字段包含应用术语表之前的常规机器翻译;glossaryTranslations 字段包含应用术语表之后的翻译。

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

// translateTextWithGlossary translates input text and returns translated text.
func translateTextWithGlossary(w io.Writer, projectID string, location string, sourceLang string, targetLang string, text string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// sourceLang := "en"
	// targetLang := "ja"
	// text := "Hello world"
	// glossaryID := "your-glossary-id"

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

	req := &translatepb.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
		GlossaryConfig: &translatepb.TranslateTextGlossaryConfig{
			Glossary: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
		},
	}

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

	// Display the translation for each input text provided
	for _, translation := range resp.GetGlossaryTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslateTextGlossaryConfig;
import com.google.cloud.translate.v3.TranslateTextRequest;
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class TranslateTextWithGlossary {

  public static void translateTextWithGlossary() 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 sourceLanguage = "your-source-language";
    String targetLanguage = "your-target-language";
    String text = "your-text";
    String glossaryId = "your-glossary-display-name";
    translateTextWithGlossary(projectId, sourceLanguage, targetLanguage, text, glossaryId);
  }

  // Translates a given text using a glossary.
  public static void translateTextWithGlossary(
      String projectId,
      String sourceLanguage,
      String targetLanguage,
      String text,
      String glossaryId)
      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)
      String location = "us-central1";
      LocationName parent = LocationName.of(projectId, location);

      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
      TranslateTextGlossaryConfig glossaryConfig =
          TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();

      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain")
              .setSourceLanguageCode(sourceLanguage)
              .setTargetLanguageCode(targetLanguage)
              .addContents(text)
              .setGlossaryConfig(glossaryConfig)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getGlossaryTranslationsList()) {
        System.out.printf("Translated text: %s\n", translation.getTranslatedText());
      }
    }
  }
}

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';
// const glossaryId = 'YOUR_GLOSSARY_ID';
// const text = 'text to translate';

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

// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateTextWithGlossary() {
  const glossaryConfig = {
    glossary: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en',
    targetLanguageCode: 'es',
    glossaryConfig: glossaryConfig,
  };

  // Run request
  const [response] = await translationClient.translateText(request);

  for (const translation of response.glossaryTranslations) {
    console.log(`Translation: ${translation.translatedText}`);
  }
}

translateTextWithGlossary();

Python

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

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


from google.cloud import translate

def translate_text_with_glossary(
    text: str = "YOUR_TEXT_TO_TRANSLATE",
    project_id: str = "YOUR_PROJECT_ID",
    glossary_id: str = "YOUR_GLOSSARY_ID",
) -> translate.TranslateTextResponse:
    """Translates a given text using a glossary.

    Args:
        text: The text to translate.
        project_id: The ID of the GCP project that owns the glossary.
        glossary_id: The ID of the glossary to use.

    Returns:
        The translated text."""
    client = translate.TranslationServiceClient()
    location = "us-central1"
    parent = f"projects/{project_id}/locations/{location}"

    glossary = client.glossary_path(
        project_id, "us-central1", glossary_id  # The location of the glossary
    )

    glossary_config = translate.TranslateTextGlossaryConfig(glossary=glossary)

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.translate_text(
        request={
            "contents": [text],
            "target_language_code": "ja",
            "source_language_code": "en",
            "parent": parent,
            "glossary_config": glossary_config,
        }
    )

    print("Translated text: \n")
    for translation in response.glossary_translations:
        print(f"\t {translation.translated_text}")

    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
  • glossary-id:您的术语表 ID,例如“ my-en-to-ru-glossary”

HTTP 方法和网址:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id

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

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

{
  "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
  "languagePair": {
    "sourceLanguageCode": "en",
    "targetLanguageCode": "ru"
  },
  "inputConfig": {
    "gcsSource": {
  "inputUri": "gs://bucket-name/glossary-file-name"
    }
  },
  "entryCount": 9603
}

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

// getGlossary gets the specified glossary.
func getGlossary(w io.Writer, projectID string, location string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "glossary-id"

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

	req := &translatepb.GetGlossaryRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
	}

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

	fmt.Fprintf(w, "Glossary name: %v\n", resp.GetName())
	fmt.Fprintf(w, "Entry count: %v\n", resp.GetEntryCount())
	fmt.Fprintf(w, "Input URI: %v\n", resp.GetInputConfig().GetGcsSource().GetInputUri())

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GetGlossaryRequest;
import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetGlossary {

  public static void getGlossary() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    getGlossary(projectId, glossaryId);
  }

  // Get a particular glossary based on the glossary ID
  public static void getGlossary(String projectId, String glossaryId) 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)
      GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
      GetGlossaryRequest request =
          GetGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();

      Glossary response = client.getGlossary(request);

      System.out.printf("Glossary name: %s\n", response.getName());
      System.out.printf("Entry count: %s\n", response.getEntryCount());
      System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri());
    }
  }
}

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';
// const glossaryId = 'YOUR_GLOSSARY_ID';

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

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

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

  // Get glossary
  const [response] = await translationClient.getGlossary(request);

  console.log(`Glossary name: ${response.name}`);
  console.log(`Entry count: ${response.entryCount}`);
  console.log(`Input URI: ${response.inputConfig.gcsSource.inputUri}`);
}

getGlossary();

Python

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

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

from google.cloud import translate_v3 as translate

def get_glossary(
    project_id: str = "YOUR_PROJECT_ID", glossary_id: str = "YOUR_GLOSSARY_ID"
) -> translate.Glossary:
    """Get a particular glossary based on the glossary ID.

    Args:
        project_id: The GCP project ID.
        glossary_id: The ID of the glossary to retrieve.

    Returns:
        The glossary.
    """
    client = translate.TranslationServiceClient()

    name = client.glossary_path(project_id, "us-central1", glossary_id)

    response = client.get_glossary(name=name)
    print(f"Glossary name: {response.name}")
    print(f"Entry count: {response.entry_count}")
    print(f"Input URI: {response.input_config.gcs_source.input_uri}")

    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/us-central1/glossaries

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

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

{
  "glossaries": [
    {
      "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
      "languagePair": {
        "sourceLanguageCode": "en",
        "targetLanguageCode": "ru"
      },
      "inputConfig": {
        "gcsSource": {
          "inputUri": "gs://bucket-name/glossary-file-name"
        }
      },
      "entryCount": 9603
    },
    ...
  ]
}

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"
	"google.golang.org/api/iterator"
)

// listGlossaries gets the specified glossary.
func listGlossaries(w io.Writer, projectID string, location string) error {
	// projectID := "my-project-id"
	// location := "us-central1"

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

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

	it := client.ListGlossaries(ctx, req)

	// Iterate over all results
	for {
		glossary, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListGlossaries.Next: %w", err)
		}
		fmt.Fprintf(w, "Name: %v\n", glossary.GetName())
		fmt.Fprintf(w, "Entry count: %v\n", glossary.GetEntryCount())
		fmt.Fprintf(w, "Input URI: %v\n", glossary.GetInputConfig().GetGcsSource().GetInputUri())
		for _, languageCode := range glossary.GetLanguageCodesSet().GetLanguageCodes() {
			fmt.Fprintf(w, "Language code: %v\n", languageCode)
		}
		if languagePair := glossary.GetLanguagePair(); languagePair != nil {
			fmt.Fprintf(w, "Language pair: %v, %v\n",
				languagePair.GetSourceLanguageCode(), languagePair.GetTargetLanguageCode())
		}
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.ListGlossariesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class ListGlossaries {

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

  // List all the glossaries in a specified location
  public static void listGlossaries(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, "us-central1");
      ListGlossariesRequest request =
          ListGlossariesRequest.newBuilder().setParent(parent.toString()).build();

      for (Glossary responseItem : client.listGlossaries(request).iterateAll()) {
        System.out.printf("Glossary name: %s\n", responseItem.getName());
        System.out.printf("Entry count: %s\n", responseItem.getEntryCount());
        System.out.printf(
            "Input URI: %s\n", responseItem.getInputConfig().getGcsSource().getInputUri());
      }
    }
  }
}

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 listGlossaries() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  // Run request
  const [response] = await translationClient.listGlossaries(request);

  for (const glossary of response) {
    console.log(`Name: ${glossary.name}`);
    console.log(`Entry count: ${glossary.entryCount}`);
    console.log(`Input uri: ${glossary.inputConfig.gcsSource.inputUri}`);
    for (const languageCode of glossary.languageCodesSet.languageCodes) {
      console.log(`Language code: ${languageCode}`);
    }
  }
}

listGlossaries();

Python

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

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

from google.cloud import translate

def list_glossaries(project_id: str = "YOUR_PROJECT_ID") -> translate.Glossary:
    """List Glossaries.

    Args:
        project_id: The GCP project ID.

    Returns:
        The glossary.
    """
    client = translate.TranslationServiceClient()

    location = "us-central1"

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

    # Iterate over all results
    for glossary in client.list_glossaries(parent=parent):
        print(f"Name: {glossary.name}")
        print(f"Entry count: {glossary.entry_count}")
        print(f"Input uri: {glossary.input_config.gcs_source.input_uri}")

        # Note: You can create a glossary using one of two modes:
        # language_code_set or language_pair. When listing the information for
        # a glossary, you can only get information for the mode you used
        # when creating the glossary.
        for language_code in glossary.language_codes_set.language_codes:
            print(f"Language code: {language_code}")

    return glossary

其他语言

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

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

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

更新术语表

您可以通过更新术语表来更改其名称,或者使用新的术语表输入文件替换术语表的所有条目。如果您需要回滚术语表条目的更改,则必须使用原始术语表文件替换修改后的术语表。

REST

如需更新术语表,请使用 glossary.patch 方法发送 PATCH 请求。以下示例更新等效术语集术语表。使用 list 方法查找特定术语表的 ID。

update_mask 查询参数指定您是要更新术语表输入文件、术语表显示名还是两者都更新。至少需要一个更新掩码参数。

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID。
  • LOCATION:要更新的术语表所在的区域,例如 us-central1
  • GLOSSARY_ID:现有术语表的 ID。
  • LANGUAGE_CODE语言代码,用于指定此等效术语集术语的语言。
  • GLOSSARY_FILE_PATH:术语表输入文件的位置和文件名。

HTTP 方法和网址:

PATCH https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID?update_mask=input_config&update_mask=display_name

请求 JSON 正文:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID",
  "languageCodesSet": {
    "languageCodes": ["LANGUAGE_CODE", ...]
  },
  "inputConfig": {
    "gcsSource": {
      "inputUri": "gs://GLOSSARY_FILE_PATH"
    }
  }
}

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

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3.UpdateGlossaryMetadata",
    "glossary": {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID",
      "languageCodesSet": {
        "languageCodes": ["LANGUAGE_CODE", ...]
      },
      "inputConfig": {
        "gcsSource": {
        "inputUri": "gs://GLOSSARY_FILE_PATH"
        }
      },
      "entryCount": NUMBER_OF_ENTRIES,
      "submitTime": "2022-04-22T23:16:30.628806944Z",
      "endTime": "2022-04-22T23:41:15.115797Z",
      "displayName": "GLOSSARY_ID"
    },
    "state": "RUNNING",
    "submitTime": "2022-04-22T23:50:24.337964527Z"
  }
}

其他语言

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

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

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

删除术语表

以下示例将删除术语表。

REST

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID
  • glossary-id:您的术语表 ID

HTTP 方法和网址:

DELETE https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id

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

您应该会收到一个成功的状态代码 (2xx) 和一个空响应。

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

// deleteGlossary deletes a glossary.
func deleteGlossary(w io.Writer, projectID string, location string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "glossary-id"

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

	req := &translatepb.DeleteGlossaryRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
	}

	// The DeleteGlossary operation is async.
	op, err := client.DeleteGlossary(ctx, req)
	if err != nil {
		return fmt.Errorf("DeleteGlossary: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

	fmt.Fprintf(w, "Deleted: %v\n", resp.GetName())

	return nil
}

Java

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

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

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.translate.v3.DeleteGlossaryMetadata;
import com.google.cloud.translate.v3.DeleteGlossaryRequest;
import com.google.cloud.translate.v3.DeleteGlossaryResponse;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class DeleteGlossary {

  public static void deleteGlossary() throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    deleteGlossary(projectId, glossaryId);
  }

  // Delete a specific glossary based on the glossary ID
  public static void deleteGlossary(String projectId, String glossaryId)
      throws InterruptedException, ExecutionException, 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)
      GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
      DeleteGlossaryRequest request =
          DeleteGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();

      // Start an asynchronous request
      OperationFuture<DeleteGlossaryResponse, DeleteGlossaryMetadata> future =
          client.deleteGlossaryAsync(request);

      System.out.println("Waiting for operation to complete...");
      DeleteGlossaryResponse response = future.get();
      System.out.format("Deleted Glossary: %s\n", response.getName());
    }
  }
}

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';
// const glossaryId = 'YOUR_GLOSSARY_ID';

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

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

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

  // Delete glossary using a long-running operation
  const [operation] = await translationClient.deleteGlossary(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();

  console.log(`Deleted glossary: ${response.name}`);
}

deleteGlossary();

Python

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

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

from google.cloud import translate_v3 as translate

def delete_glossary(
    project_id: str = "YOUR_PROJECT_ID",
    glossary_id: str = "YOUR_GLOSSARY_ID",
    timeout: int = 180,
) -> translate.Glossary:
    """Delete a specific glossary based on the glossary ID.

    Args:
        project_id: The ID of the GCP project that owns the glossary.
        glossary_id: The ID of the glossary to delete.
        timeout: The timeout for this request.

    Returns:
        The glossary that was deleted.
    """
    client = translate.TranslationServiceClient()

    name = client.glossary_path(project_id, "us-central1", glossary_id)

    operation = client.delete_glossary(name=name)
    result = operation.result(timeout)
    print(f"Deleted: {result.name}")

    return result

其他语言

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

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

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

管理术语表条目

术语表条目将一种语言的术语映射到另一种语言的术语。您可以向术语表添加新条目、列出现有术语表的所有条目或修改现有条目。

创建新条目

创建新条目以向现有术语表添加术语。对于单向术语表,请提供术语对,其中一个术语为源语言,另一个术语为目标语言。对于等效术语集术语表,请提供术语集,集中的每一项都指定一个术语及其语言代码。

REST

以下示例为等效术语集术语表创建一个条目。每个请求只能创建一个条目。如需了解详情,请参阅 glossaryEntries.create 方法。

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID。
  • LOCATION:要更新的术语表所在的区域,例如 us-central1
  • GLOSSARY_ID:现有术语表的 ID。
  • LANGUAGE_CODE:指定术语语言的语言代码
  • TERM:要添加到术语表的术语。
  • DESCRIPTION:术语表条目的相关信息。

HTTP 方法和网址:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries

请求 JSON 正文:

{
  termsSet: {
   terms: {
     languageCode: "LANGUAGE_CODE",
     text: "TERM"
    },
    ...
  },
  description: "DESCRIPTION"
}

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

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

其他语言

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

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

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

列出术语表条目

列出现有术语表的所有条目。例如,如果您想要检查特定术语表中的哪些术语和哪些语言,这会非常有用。

REST

如需列出所有术语表条目,请使用 glossaryEntries.list 方法发送 GET 请求。

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID。
  • LOCATION:要更新的术语表所在的区域,例如 us-central1
  • GLOSSARY_ID:现有术语表的 ID。

HTTP 方法和网址:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries

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

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

{
  "glossaryEntries": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
      "termsSet": {
        "terms": [
          {
            "languageCode": "LANGUAGE_CODE",
            "text": "TERM"
          },
        ...
        ]
      },
      "description": "DESCRIPTION"
    },
    ...
  ]
}

其他语言

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

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

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

获取术语表条目

获取单个条目以查看其信息。

REST

如需获取单个术语表条目,请使用 glossaryEntries.get 方法发送 GET 请求。使用 list 方法查找特定条目的 ID。

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID。
  • LOCATION:要更新的术语表所在的区域,例如 us-central1
  • GLOSSARY_ID:现有术语表的 ID。
  • GLOSSARY_ENTRY_ID:现有术语表条目的 ID。

HTTP 方法和网址:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

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

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

其他语言

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

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

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

更新术语表条目

您可以更新单个条目或替换术语表中的所有条目。如需替换所有条目,请参阅更新术语表

如需修改单向术语表中的条目,请提供术语对,其中一个术语为源语言,另一个术语为目标语言。对于等效术语集术语表,请提供术语集,集中的每一项都指定一个术语及其语言代码。

REST

以下示例更新等效术语集术语表的条目。如需了解详情,请参阅 glossaryEntries.patch 方法。

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID。
  • LOCATION:要更新的术语表所在的区域,例如 us-central1
  • GLOSSARY_ID:包含要更新之条目的现有术语表的 ID。
  • GLOSSARY_ENTRY_ID:要更新之术语表条目的 ID。
  • LANGUAGE_CODE:指定术语语言的语言代码
  • TERM:要更新的术语。
  • DESCRIPTION:术语表条目的相关信息。

HTTP 方法和网址:

PATCH https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

请求 JSON 正文:

{
  termsSet: {
   terms: {
     languageCode: "LANGUAGE_CODE",
     text: "TERM"
    },
    ...
  },
  description: "DESCRIPTION"
}

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

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

其他语言

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

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

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

删除术语表条目

移除单个术语表条目。

REST

如需删除单个术语表条目,请使用 glossaryEntries.delete 方法发送 DELETE 请求。使用 list 方法查找特定条目的 ID。

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

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 项目的数字或字母数字 ID。
  • LOCATION:要更新的术语表所在的区域,例如 us-central1
  • GLOSSARY_ID:包含要删除之条目的现有术语表的 ID。
  • GLOSSARY_ENTRY_ID:要删除之术语表条目的 ID。

HTTP 方法和网址:

DELETE https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

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

您应该会收到一个成功的状态代码 (2xx) 和一个空响应。

其他语言

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

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

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

其他资源

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