建立及使用詞彙表 (進階)

「詞彙表」是一種自訂字典,可用來協助 Cloud Translation API 一致地翻譯客戶的特定領域專有術語。這通常涉及指定如何翻譯具名實體。

您可能會在下列情況使用字彙表:

  • 產品名稱:例如「Google Home」必須翻譯為「Google Home」。
  • 含糊不清的字詞:舉例來說,「蝙蝠」一詞可以指運動器材,也可以指動物。如果您知道自己要翻譯的字詞與運動有關,可能就會想使用詞彙表,將「bat」的運動翻譯提供給 Cloud Translation API,而不是動物的翻譯。
  • 借用字:例如,法文的「bouillabaisse」翻譯成英文時,仍是「bouillabaisse」。英文在 19 世紀時從法文借用了「bouillabaisse」一字。如果說英語的人不瞭解法國文化背景,可能不知道 bouillabaisse 是魚肉燉湯。詞彙表可以覆寫翻譯,因此法文的「bouillabaisse」會翻譯成英文的「fish stew」。

事前準備

如要開始使用 Cloud Translation API,您必須擁有已啟用 Cloud Translation API 的專案,並具備適當的憑證。您也可以安裝常用程式設計語言的用戶端程式庫,協助您呼叫 API。詳情請參閱「設定」頁面。

所需權限

如要使用字彙表,服務帳戶必須具備字彙表專屬權限。您可以使用其中一個預先定義的身分與存取權管理角色 (例如 Cloud Translation API 編輯者 (roles/cloudtranslate.editor)),為服務帳戶授予相關角色,或是建立自訂角色來授予必要權限。您可以在身分與存取權管理權限參考資料中查看所有 Cloud Translation API 權限。 Cloud Translation 權限的開頭為 cloudtranslate

如要建立字彙表,您也需要權限讀取 Cloud Storage 值區中的物件 (字彙表檔案所在位置)。您可以透過其中一個預先定義的身分與存取權管理角色 (例如 Storage 物件檢視者 (roles/storage.objectViewer)),為服務帳戶授予角色,也可以建立自訂角色,授予讀取物件的權限。

如要瞭解如何為角色新增帳戶,請參閱授予、變更及撤銷資源存取權

建立詞彙集

詞彙表中的字詞可以是單一符記 (字詞) 或簡短詞組 (通常五個字以下)。使用詞彙表的主要步驟為:

  1. 建立詞彙表檔案
  2. 使用 Cloud Translation API 建立詞彙表資源
  3. 指定在要求翻譯時要使用的詞彙表

一個專案可以有多個詞彙表。您可以取得可用詞彙表清單,也可以刪除不再需要的詞彙表

非檢索用字

Cloud Translation 會忽略詞彙表中的某些字詞,這些字詞稱為「停用字」。翻譯停用字時,Cloud Translation 會忽略任何相符的詞彙表項目。如需所有停用字的清單,請參閱「字彙表停用字」。

建立詞彙表檔案

詞彙表基本上是一個文字檔,檔案中的每一行包含數種語言的對應詞彙。Cloud Translation API 支援「單向」詞彙表,也就是指定一組原文與譯文語言的所需譯法。此外也支援「對等字詞集」,可標示多種語言的對等字詞。

詞彙表輸入檔案中的字詞總數,不得超過 1040 萬個 (10,485,760) 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 略過的無效 <tu> 元素超過 1024 個,也會取消處理作業。

對等字詞集 (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 則是您提供的詞彙表 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

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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 - Advanced 中,您需要明確指定用來翻譯文字內容的翻譯模型。您可以搭配詞彙表呼叫 Translation LLM、NMT 和自訂模型,但只有 Translation LLM 支援搭配情境詞彙表,提供最新品質提升功能。如要套用這項功能,請將 BOOLEAN_CONTEXTUAL 設為 TRUE。您也可以標示用於特定領域專有術語的詞彙表。

REST

以下範例使用預設的 NMT 模型和詞彙表來翻譯文字。

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER_OR_ID:專案的數值或英數字元 ID。 Google Cloud
  • GLOSSARY_ID:您的詞彙表 ID,例如 my-en-ru-glossary
  • BOOLEAN:比對時是否不區分大小寫。根據預設,這個值為 false
  • BOOLEAN_CONTEXTUAL:是否在術語表翻譯中考量情境。根據預設,這個值為 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,
    "contextual_translation_enabled": BOOLEAN_CONTEXTUAL
  }
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

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

translations 欄位包含尚未套用詞彙表的一般機器翻譯,而 glossaryTranslations 欄位則包含套用詞彙表後的翻譯。將 contextual_translation_enabled 欄位設為 true 時,回應只會包含 glossaryTranslations 欄位,不會包含 translations 欄位。

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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 參考文件

使用詞彙表進行 Adaptive Translation

如要在自動調整翻譯要求中使用詞彙表,請在要求中加入詞彙表設定。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER_OR_ID:您的 Google Cloud 專案的數值或英數字元 ID
  • LOCATION:來源資料集所在的區域,例如 us-central1
  • DATASET_NAME:Cloud Translation 用於自訂翻譯內容的資料集名稱,格式為 projects/PROJECT_ID/locations/LOCATION/adaptiveMtDatasets/DATASET_ID。您可以列出專案中的所有資料集,取得資料集名稱。
  • SOURCE_TEXT:要翻譯的文字。
  • MIME_TYPE (選用):來源文字的格式,例如 text/htmltext/plain。根據預設,MIME 類型會設為 text/plain
  • GLOSSARY_ID:您的詞彙表 ID,例如 my-en-ru-glossary
  • BOOLEAN (選用):比對時是否不區分大小寫。根據預設,這個值為 false
  • BOOLEAN_CONTEXTUAL (選用):是否在術語翻譯中考量情境。根據預設,這個值為 false

HTTP 方法和網址:

POST https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:adaptiveMtTranslate

JSON 要求主體:

{
  "dataset": "DATASET_NAME",
  "content": ["SOURCE_TEXT"],
  "mimeType": "MIME_TYPE",
  "glossaryConfig": {
    "glossary": "projects/project-number/locations/LOCATION/glossaries/GLOSSARY_ID",
    "ignoreCase": BOOLEAN,
    "contextual_translation_enabled": BOOLEAN_CONTEXTUAL
  }
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "translations": [
    {
      "translatedText": "TRANSLATED_TEXT"
    }
  ],
  "languageCode": "TARGET_LANGUAGE",
  "glossaryTranslations": {
    "translatedText": "TRANSLATED_TEXT",
    "glossaryConfig": {
      "glossary": "projects/project-number/locations/LOCATION/glossaries/GLOSSARY_ID",
      "ignoreCase": BOOLEAN,
      "contextual_translation_enabled": BOOLEAN_CONTEXTUAL
    }
  },
}

Java

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Java API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

  {% dynamic setvar launch_stage %}preview{% dynamic endsetvar %}
{% dynamic setvar launch_type %}feature{% dynamic endsetvar %}
{% include "cloud/_shared/_info_launch_stage_disclaimer.html" %}

/** Translates using AdaptiveMt. */
private static void adaptiveMtTranslate(
    TranslationServiceClient translationServiceClient, String projectId, String datasetId) {
  String adaptiveMtDatasetName =
      String.format(
          "projects/%s/locations/LOCATION/adaptiveMtDatasets/%s", projectId, datasetId);
  String glossaryId = "your-glossary-display-name";
  GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
  GlossaryConfig glossaryConfig =
      GlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();

  AdaptiveMtTranslateRequest request =
      AdaptiveMtTranslateRequest.newBuilder()
          .setParent(LocationName.of(projectId, "us-central1").toString())
          .setDataset(adaptiveMtDatasetName)
          .addContent("Sample translation text")
          .setGlossaryConfig(glossaryConfig)
          .build();
  AdaptiveMtTranslateResponse response = translationServiceClient.adaptiveMtTranslate(request);

  System.out.println("Translating using AdaptiveMt");
  System.out.println(response);
}



  

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Node.js API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

  async function translate() {
  /**
  * TODO(developer): Uncomment these variables before running the sample.
  */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';
  // const glossaryId = 'YOUR_GLOSSARY_ID';

  const glossaryConfig = {
    glossary: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    dataset: `projects/${projectId}/locations/${location}/adaptiveMtDatasets/${
        adaptiveMtDatasetName}`,
    content: ['Sample translate query'],
    glossaryConfig: glossaryConfig,
  } const [response] = await translationClient.adaptiveMtTranslate(request)
  console.log('Translating')
  console.log(response)
}
  

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Python API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

  def adaptive_mt_translate(
    project_id: str = "YOUR_PROJECT_ID",
    glossary_id: str = "YOUR_GLOSSARY_ID"):
    # Create a client
    client = translate.TranslationServiceClient()
    # Create a glossary
    glossary = client.glossary_path(
        project_id, "us-central1", glossary_id  # The location of the glossary
    )

    glossary_config = translate.GlossaryConfig(glossary=glossary)
    # Initialize the request
    request = translate.AdaptiveMtTranslateRequest(
        parent="projects/PROJECT_ID/locations/LOCATION",
        dataset="projects/PROJECT_ID/locations/LOCATION/adaptiveMtDatasets/DATASET_ID",
        content=["Sample translation request"]
        glossary_config=glossary_config,
    )
    # Make the request
    response = client.adaptive_mt_translate(request)
    # Handle the response
    print(response)
  

取得詞彙表的相關資訊

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

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

下列範例會列出與指定專案相關聯的所有詞彙表。 <x0A> <0x0

使用任何要求資料之前,請先替換以下項目:

  • 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

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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:專案的數值或英數字元 ID。 Google Cloud
  • 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

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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:專案的數值或英數字元 ID。 Google Cloud
  • 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:專案的數值或英數字元 ID。 Google Cloud
  • 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 要求。使用清單方法找出特定項目的 ID。

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER_OR_ID:專案的數值或英數字元 ID。 Google Cloud
  • 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:專案的數值或英數字元 ID。 Google Cloud
  • 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 要求。使用清單方法找出特定項目的 ID。

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER_OR_ID:專案的數值或英數字元 ID。 Google Cloud
  • 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 參考文件

其他資源

  • 如需解決常見問題或錯誤的說明,請參閱「疑難排解」頁面。