偵測語言 (基本)

本文說明如何使用 Cloud Translation - Basic (v2) 偵測字串的語言。

事前準備

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

限制

語言偵測功能不支援 fr-CR 和 pt-BR。

偵測文字字串的語言

您可以使用下列格式的網址傳送 HTTP 要求,偵測文字字串的語言:

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

偵測單一字串的語言

REST

如要偵測某些文字的語言,請發出 POST 要求並提供適當的要求主體。以下為使用 curl 或 PowerShell 的 POST 要求範例。範例中使用的存取憑證,屬於使用 Google Cloud CLI 建立的專案服務帳戶。如需安裝 Google Cloud CLI、使用服務帳戶建立專案,以及取得存取憑證的操作說明,請參閱「設定」頁面。

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 專案的數值或英數字元 ID

HTTP 方法和網址:

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

JSON 要求主體:

{
  "q": "Mi comida favorita es una enchilada."
}

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

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

{
  "data": {
    "detections": [
      [
        {
          "confidence": 1,
          "isReliable": false,
          "language": "es"
        }
      ]
    ]
  }
}

回覆中的 language 是偵測到的語言代碼,其他兩個欄位 (isReliableconfidence) 是為了具備回溯相容性而加入的已淘汰欄位。建議不要按照這些欄位的值來做出任何決策或設定門檻。

Go

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

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

import (
	"context"
	"fmt"

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

func detectLanguage(text string) (*translate.Detection, error) {
	// text := "こんにちは世界"
	ctx := context.Background()
	client, err := translate.NewCtranslate.NewClient!= nil {
		return nil, fmt.Errorf("translate.NewClient: %w", err)
	}
	defer client.Close()
	lang, err := client.DetectLanguage(ctx, []string{text})
	if err != nil {
		return nil, fmt.Errorf("DetectLanguage: %w", err)
	}
	if len(lang) == 0 || len(lang[0]) == 0 {
		return nil, fmt.Errorf("DetectLanguage return value empty")
	}
	return &lang[0][0], nil
}

Java

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

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

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

List<String> texts = new LinkedList<>();
texts.add("Hello, World!");
texts.add("¡Hola Mundo!");
List<Detection> detections = translate.detect(texts);

System.out.println("Language(s) detected:");
for (Detection detection : detections) {
  System.out.printf("\t%s\n", detection);
}

Node.js

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

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

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const text = 'The text for which to detect language, e.g. Hello, world!';

// Detects the language. "text" can be a string for detecting the language of
// a single piece of text, or an array of strings for detecting the languages
// of multiple texts.
async function detectLanguage() {
  let [detections] = await translate.detect(text);
  detections = Array.isArray(detections) ? detections : [detections];
  console.log('Detections:');
  detections.forEach(detection => {
    console.log(`${detection.input} => ${detection.language}`);
  });
}

detectLanguage();

Python

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

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

def detect_language(text: str) -> dict:
    """Detects the text's language."""
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    # Text can also be a sequence of strings, in which case this method
    # will return a sequence of results for each text.
    result = translate_client.detect_language(text)

    print(f"Text: {text}")
    print("Confidence: {}".format(result["confidence"]))
    print("Language: {}".format(result["language"]))

    return result

其他語言

C#: 請按照用戶端程式庫頁面的 C# 設定說明操作, 然後前往 .NET 適用的 Cloud Translation 參考說明文件

PHP: 請按照用戶端程式庫頁面的 PHP 設定說明 操作,然後前往 PHP 適用的 Cloud Translation 參考說明文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明 操作,然後前往 Ruby 適用的 Cloud Translation 參考文件

偵測多個字串的語言

REST

如要偵測多個字串的語言,請使用 q 參數指定每個字串。這個範例會傳遞兩個不同的字串以供偵測:

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 專案的數值或英數字元 ID

HTTP 方法和網址:

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

JSON 要求主體:

{
  "q": ["Hello world", "我的名字叫傑夫"]
}

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

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

{
  "data": {
    "detections": [
      [
        {
          "confidence": 1,
          "isReliable": false,
          "language": "en"
        }
      ],
      [
        {
          "confidence": 1,
          "isReliable": false,
          "language": "zh-TW"
        }
      ]
    ]
  }
}

在此,回應中包含兩個偵測,其順序與之前在要求中提供對應來源字串的順序相同。

Go

如要偵測多個字串的語言,請在傳遞至上例所示 Client#DetectLanguage 方法的切片中加入多個字串。

Java

如要偵測多個字串的語言,請直接將字串清單傳送到上例所示的 Translate#detect 方法。

Node.js

如要偵測多個字串的語言,請直接將字串陣列傳送到上例所示的 Translate#detect 方法。

Python

如要偵測多個字串的語言,請直接將字串清單傳送到上例所示的 Client#detect_language 方法。

其他語言

C#: 請按照用戶端程式庫頁面的 C# 設定說明操作, 然後前往 .NET 適用的 Cloud Translation 參考說明文件

PHP: 請按照用戶端程式庫頁面的 PHP 設定說明 操作,然後前往 PHP 適用的 Cloud Translation 參考說明文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明 操作,然後前往 Ruby 適用的 Cloud Translation 參考文件

Ruby

如要偵測多個字串的語言,請直接將多個字串傳送到上例所示的 Translate#detect 方法。

其他資源

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