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

术语表是一种自定义字典,用于确保 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 权限。Translation 权限以 cloudtranslate 开头。

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

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

创建术语表

术语表中的术语可以是单个词条(单词)或短语(通常少于五个单词)。每个项目的独立术语表数量的当前上限为 1000。

如需使用术语表,您需要执行以下主要步骤:

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

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

创建术语表文件

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

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

单向术语表

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

制表符分隔值 (TSV)

Cloud Translation API 支持以制表符分隔的文件,其中每一行都采用以下格式:

  • Term in source language 制表符 Term in target language

例如:

account\tcuenta
directions\tindicaciones

制表符分隔的源数据不包含用于标识源语言和目标语言的语言代码。您可在创建术语库时标识源语言和目标语言。

逗号分隔值 (CSV)

对于 CSV 文件中的每一行,请使用英文逗号 (,) 分隔源语言术语和目标语言术语,如以下示例所示:

account,cuenta
directions,indicaciones

请勿在 CSV 文件中添加标题行以标识源语言和目标语言。您可以在创建术语库时标识它们。

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-1 代码来标识源语言和目标语言。

所有 <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-639-1BCP-47 语言代码标识每一列对应的语言。您还可以选择添加词性 (pos) 列和说明 (description) 列。

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

等效术语集

创建术语表资源

确定等效术语表术语以后,您可以通过创建术语表资源,使术语表文件可用于 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"
    }
  }
}

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

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/v3/projects/project-number-or-id/locations/us-central1/glossaries

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/v3/projects/project-number-or-id/locations/us-central1/glossaries " | Select-Object -Expand Content

您应该收到类似以下内容的 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"
    }
  }
}

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

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/v3/projects/project-number-or-id/locations/us-central1/glossaries

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/v3/projects/project-number-or-id/locations/us-central1/glossaries " | Select-Object -Expand Content

您应该收到类似以下内容的 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"
  }
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class CreateGlossary
    {
        /// <summary>
        /// Create Glossary.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="glossaryId">Your glossary display name.</param>
        /// <param name="inputUri">Google Cloud Storage URI where glossary is stored in csv format.</param>
        public static void CreateGlossarySample(string projectId = "[Google Cloud Project ID]",
            string glossaryId = "your-glossary-display-name",
            string inputUri = "gs://cloud-samples-data/translation/glossary_ja.csv")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            CreateGlossaryRequest request = new CreateGlossaryRequest
            {
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
                Parent = new LocationName(projectId, "us-central1").ToString(),
                Glossary = new Glossary
                {
                    Name = new GlossaryName(projectId, "us-central1", glossaryId).ToString(),
                    LanguageCodesSet = new Glossary.Types.LanguageCodesSet
                    {
                        LanguageCodes =
                        {
                            "en", // source lang
                            "ja", // target lang
                        },
                    },
                    InputConfig = new GlossaryInputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                    },
                },
            };
            // Poll until the returned long-running operation is complete
            Glossary response = translationServiceClient.CreateGlossary(request).PollUntilCompleted().Result;
            Console.WriteLine("Created Glossary.");
            Console.WriteLine($"Glossary name: {response.Name}");
            Console.WriteLine($"Entry count: {response.EntryCount}");
            Console.WriteLine($"Input URI: {response.InputConfig.GcsSource.InputUri}");
        }
    }

Go

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

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// 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: %v", 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: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

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

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

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

/**
 * 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,
  };

  try {
    // 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}`
    );
  } catch (error) {
    console.error(error.details);
  }
}

createGlossary();

PHP

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

use Google\Cloud\Translate\V3\GcsSource;
use Google\Cloud\Translate\V3\Glossary;
use Google\Cloud\Translate\V3\GlossaryInputConfig;
use Google\Cloud\Translate\V3\Glossary\LanguageCodesSet;
use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $glossaryId = 'my_glossary_id_123';
// $inputUri = 'gs://cloud-samples-data/translation/glossary.csv';
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    'us-central1'
);
$formattedName = $translationServiceClient->glossaryName(
    $projectId,
    'us-central1',
    $glossaryId
);
$languageCodesElement = 'en';
$languageCodesElement2 = 'ja';
$languageCodes = [$languageCodesElement, $languageCodesElement2];
$languageCodesSet = new LanguageCodesSet();
$languageCodesSet->setLanguageCodes($languageCodes);
$gcsSource = (new GcsSource())
    ->setInputUri($inputUri);
$inputConfig = (new GlossaryInputConfig())
    ->setGcsSource($gcsSource);
$glossary = (new Glossary())
    ->setName($formattedName)
    ->setLanguageCodesSet($languageCodesSet)
    ->setInputConfig($inputConfig);

try {
    $operationResponse = $translationServiceClient->createGlossary(
        $formattedParent,
        $glossary
    );
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $response = $operationResponse->getResult();
        printf('Created Glossary.' . PHP_EOL);
        printf('Glossary name: %s' . PHP_EOL, $response->getName());
        printf('Entry count: %s' . PHP_EOL, $response->getEntryCount());
        printf(
            'Input URI: %s' . PHP_EOL,
            $response->getInputConfig()
                ->getGcsSource()
                ->getInputUri()
        );
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
} finally {
    $translationServiceClient->close();
}

Python

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

from google.cloud import translate_v3 as translate

def create_glossary(
    project_id="YOUR_PROJECT_ID",
    input_uri="YOUR_INPUT_URI",
    glossary_id="YOUR_GLOSSARY_ID",
    timeout=180,
):
    """
    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("Created: {}".format(result.name))
    print("Input Uri: {}".format(result.input_config.gcs_source.input_uri))

Ruby

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

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"
# glossary_id = "your-glossary-display-name"

client = Google::Cloud::Translate.translation_service

input_uri = "gs://cloud-samples-data/translation/glossary_ja.csv"

parent = client.location_path project: project_id, location: location_id
glossary_name = client.glossary_path project:  project_id,
                                     location: location_id,
                                     glossary: glossary_id
language_codes_set = { language_codes: ["en", "ja"] }
input_config = { gcs_source: { input_uri: input_uri } }
glossary = {
  name:               glossary_name,
  language_codes_set: language_codes_set,
  input_config:       input_config
}

operation = client.create_glossary parent: parent, glossary: glossary
# Wait until the long running operation is done
operation.wait_until_done!
response = operation.response

puts "Created Glossary."
puts "Glossary name: #{response.name}"
puts "Entry count: #{response.entry_count}"
puts "Input URI: #{response.input_config.gcs_source.input_uri}"

操作状态

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

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

使用术语表

使用术语表翻译文本

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

REST 和命令行

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

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

  • project-number-or-id:您的 Google Cloud 项目编号或 ID
  • glossary-id:您的术语库 ID,例如 my-en-ru-g 术语库

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

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

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/v3/projects/project-number-or-id/locations/us-central1:translateText

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/v3/projects/project-number-or-id/locations/us-central1:translateText " | Select-Object -Expand Content

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

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

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

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class TranslateTextWithGlossary
    {
        /// <summary>
        /// Translates a given text to a target language using glossary.
        /// </summary>
        /// <param name="text">The content to translate.</param>
        /// <param name="sourceLanguage">Optional. Source language code.</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="glossaryId">Translation Glossary ID.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void TranslateTextWithGlossarySample(
            string text = "[TEXT_TO_TRANSLATE]",
            string sourceLanguage = "en",
            string targetLanguage = "ja",
            string projectId = "[Google Cloud Project ID]",
            string glossaryId = "[YOUR_GLOSSARY_ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();

            string glossaryPath = $"projects/{projectId}/locations/{"us-central1"}/glossaries/{glossaryId}";
            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
                SourceLanguageCode = sourceLanguage,
                GlossaryConfig = new TranslateTextGlossaryConfig
                {
                    // Translation Glossary Path.
                    Glossary = glossaryPath,
                },
                MimeType = "text/plain",
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);
            // Display the translation for given content.
            foreach (Translation translation in response.GlossaryTranslations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
    }

Go

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

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// 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: %v", 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: %v", 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

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

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

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

/**
 * 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,
  };

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

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

translateTextWithGlossary();

PHP

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

use Google\Cloud\Translate\V3\TranslateTextGlossaryConfig;
use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $sourceLanguage = 'en';
// $targetLanguage = 'fr';
// $projectId = '[Google Cloud Project ID]';
// $glossaryId = '[YOUR_GLOSSARY_ID]';
$glossaryPath = $translationServiceClient->glossaryName(
    $projectId,
    'us-central1',
    $glossaryId
);
$contents = [$text];
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    'us-central1'
);
$glossaryConfig = new TranslateTextGlossaryConfig();
$glossaryConfig->setGlossary($glossaryPath);

// Optional. Can be "text/plain" or "text/html".
$mimeType = 'text/plain';

try {
    $response = $translationServiceClient->translateText(
        $contents,
        $targetLanguage,
        $formattedParent,
        [
            'sourceLanguageCode' => $sourceLanguage,
            'glossaryConfig' => $glossaryConfig,
            'mimeType' => $mimeType
        ]
    );
    // Display the translation for each input text provided
    foreach ($response->getGlossaryTranslations() as $translation) {
        printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
    }
} finally {
    $translationServiceClient->close();
}

Python

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


from google.cloud import translate

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

    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("\t {}".format(translation.translated_text))

Ruby

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

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"
# glossary_id = "[YOUR_GLOSSARY_ID]"

# The content to translate in string format
contents = ["Hello, world!"]
# Required. The BCP-47 language code to use for translation.
target_language = "fr"
# Optional. The BCP-47 language code of the input text.
source_language = "en"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id
glossary_path = client.glossary_path project:  project_id,
                                     location: location_id,
                                     glossary: glossary_id
glossary_config = { glossary: glossary_path }

response = client.translate_text parent:               parent,
                                 contents:             contents,
                                 target_language_code: target_language,
                                 source_language_code: source_language,
                                 glossary_config:      glossary_config,
                                 mime_type:            mime_type

# Display the translation for each input text provided
response.glossary_translations.each do |translation|
  puts "Translated text: #{translation.translated_text}"
end

获取有关术语表的信息

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

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

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries/glossary-id

PowerShell

执行以下命令:

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries/glossary-id " | Select-Object -Expand Content

您应该收到类似以下内容的 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
}

C#

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


using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class GetGlossary
    {
        /// <summary>
        /// Retrieves a glossary.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="glossaryId">Glossary ID.</param>
        public static void GetGlossarySample(string projectId = "[Google Cloud Project ID]",
            string glossaryId = "[YOUR_GLOSSARY_ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            GetGlossaryRequest request = new GetGlossaryRequest
            {
                GlossaryName = new GlossaryName(projectId, "us-central1", glossaryId),
            };
            Glossary response = translationServiceClient.GetGlossary(request);
            Console.WriteLine($"Glossary name: {response.Name}");
            Console.WriteLine($"Entry count: {response.EntryCount}");
            Console.WriteLine($"Input URI: {response.InputConfig.GcsSource.InputUri}");
        }
    }

Go

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

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// 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: %v", 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: %v", 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

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

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

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

/**
 * 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}`,
  };

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

    console.log(`Got glossary: ${response.name}`);
  } catch (error) {
    console.error(error.details);
  }
}

getGlossary();

PHP

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

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $glossaryId = '[Glossary ID]';
$formattedName = $translationServiceClient->glossaryName(
    $projectId,
    'us-central1',
    $glossaryId
);

try {
    $response = $translationServiceClient->getGlossary($formattedName);
    printf('Glossary name: %s' . PHP_EOL, $response->getName());
    printf('Entry count: %s' . PHP_EOL, $response->getEntryCount());
    printf(
        'Input URI: %s' . PHP_EOL,
        $response->getInputConfig()
            ->getGcsSource()
            ->getInputUri()
    );
} finally {
    $translationServiceClient->close();
}

Python

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

from google.cloud import translate_v3 as translate

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

    client = translate.TranslationServiceClient()

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

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

Ruby

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

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"
# glossary_id = "[YOUR_GLOSSARY_ID]"

client = Google::Cloud::Translate.translation_service

name = client.glossary_path project:  project_id,
                            location: location_id,
                            glossary: glossary_id

response = client.get_glossary name: name

puts "Glossary name: #{response.name}"
puts "Entry count: #{response.entry_count}"
puts "Input URI: #{response.input_config.gcs_source.input_uri}"

列出术语表

一个项目可以包括若干术语表。本部分介绍如何检索特定项目的可用术语表列表。

REST 和命令行

以下示例将列出与指定项目关联的所有术语表。

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

  • project-number-or-id:您的 Google Cloud 项目编号或 ID

HTTP 方法和网址:

GET https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries

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

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries

PowerShell

执行以下命令:

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries " | Select-Object -Expand Content

您应该收到类似以下内容的 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
    },
    ...
  ]
}

C#

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


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class ListGlossary
    {
        /// <summary>
        /// Lists all the glossaries for a given project.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void ListGlossariesSample(string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            ListGlossariesRequest request = new ListGlossariesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
            };
            PagedEnumerable<ListGlossariesResponse, Glossary> response = translationServiceClient.ListGlossaries(request);
            // Iterate over glossaries and display each glossary's details.
            foreach (Glossary item in response)
            {
                Console.WriteLine($"Glossary name: {item.Name}");
                Console.WriteLine($"Entry count: {item.EntryCount}");
                Console.WriteLine($"Input URI: {item.InputConfig.GcsSource.InputUri}");
            }
        }
    }

Go

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

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	"google.golang.org/api/iterator"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// 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: %v", 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: %v", 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

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

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

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

/**
 * 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}`,
  };

  try {
    // 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}`);
      }
    }
  } catch (error) {
    console.error(error.details);
  }
}

listGlossaries();

PHP

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

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    'us-central1'
);

try {
    // Iterate through all elements
    $pagedResponse = $translationServiceClient->listGlossaries($formattedParent);
    foreach ($pagedResponse->iterateAllElements() as $responseItem) {
        printf('Glossary name: %s' . PHP_EOL, $responseItem->getName());
        printf('Entry count: %s' . PHP_EOL, $responseItem->getEntryCount());
        printf(
            'Input URI: %s' . PHP_EOL,
            $responseItem->getInputConfig()
                ->getGcsSource()
                ->getInputUri()
        );
    }
} finally {
    $translationServiceClient->close();
}

Python

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

from google.cloud import translate

def list_glossaries(project_id="YOUR_PROJECT_ID"):
    """List Glossaries."""

    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("Name: {}".format(glossary.name))
        print("Entry count: {}".format(glossary.entry_count))
        print("Input uri: {}".format(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("Language code: {}".format(language_code))

Ruby

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

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id

responses = client.list_glossaries parent: parent

responses.each do |response|
  puts "Glossary name: #{response.name}"
  puts "Entry count: #{response.entry_count}"
  puts "Input URI: #{response.input_config.gcs_source.input_uri}"
end

删除术语表

以下示例将删除术语表。

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

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

curl

执行以下命令:

curl -X DELETE \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries/glossary-id

PowerShell

执行以下命令:

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

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1/glossaries/glossary-id " | Select-Object -Expand Content

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

C#

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


using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class DeleteGlossary
    {
        /// <summary>
        /// Deletes a Glossary.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="glossaryId">Glossary ID.</param>
        public static void DeleteGlossarySample(string projectId = "[Google Cloud Project ID]",
            string glossaryId = "[YOUR_GLOSSARY_ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            DeleteGlossaryRequest request = new DeleteGlossaryRequest
            {
                GlossaryName = new GlossaryName(projectId, "us-central1", glossaryId),
            };
            // Poll until the returned long-running operation is complete
            DeleteGlossaryResponse response = translationServiceClient.DeleteGlossary(request).PollUntilCompleted().Result;
            Console.WriteLine("Deleted Glossary.");
        }
    }

Go

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

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// 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: %v", 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: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

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

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

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

/**
 * 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}`,
  };

  try {
    // 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}`);
  } catch (error) {
    console.error(error.details);
  }
}

deleteGlossary();

PHP

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

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
// $glossaryId = '[Glossary ID]';
$formattedName = $translationServiceClient->glossaryName(
    $projectId,
    'us-central1',
    $glossaryId
);

try {
    $operationResponse = $translationServiceClient->deleteGlossary($formattedName);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $response = $operationResponse->getResult();
        printf('Deleted Glossary.' . PHP_EOL);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
} finally {
    $translationServiceClient->close();
}

Python

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

from google.cloud import translate_v3 as translate

def delete_glossary(
    project_id="YOUR_PROJECT_ID", glossary_id="YOUR_GLOSSARY_ID", timeout=180,
):
    """Delete a specific glossary based on the glossary ID."""
    client = translate.TranslationServiceClient()

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

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

Ruby

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

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"
# glossary_id = "[YOUR_GLOSSARY_ID]"

client = Google::Cloud::Translate.translation_service

name = client.glossary_path project:  project_id,
                            location: location_id,
                            glossary: glossary_id

operation = client.delete_glossary name: name

# Wait until the long running operation is done
operation.wait_until_done!

puts "Deleted Glossary."