문자열 번역(기본 버전)

Cloud Translation - 기본(v2)을 사용하여 문자열을 번역합니다.

코드 샘플

Go

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Go API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

func translateTextWithModel(targetLanguage, text, model string) (string, error) {
	// targetLanguage := "ja"
	// text := "The Go Gopher is cute"
	// model := "nmt"

	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return "", fmt.Errorf("language.Parse: %w", err)
	}

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

	resp, err := client.Translate(ctx, []string{text}, lang, &translate.Options{
		Model: model, // Either "nmt" or "base".
	})
	if err != nil {
		return "", fmt.Errorf("Translate: %w", err)
	}
	if len(resp) == 0 {
		return "", nil
	}
	return resp[0].Text, nil
}

Java

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Java API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

Translation translation =
    translate.translate(
        "Hola Mundo!",
        Translate.TranslateOption.sourceLanguage("es"),
        Translate.TranslateOption.targetLanguage("de"),
        // Use "base" for standard edition, "nmt" for the premium model.
        Translate.TranslateOption.model("nmt"));

System.out.printf("TranslatedText:\nText: %s\n", translation.getTranslatedText());

Node.js

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 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 lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';
// const model = 'The model to use, e.g. nmt';

async function translateTextWithModel() {
  const options = {
    // The target language, e.g. "ru"
    to: target,
    // Make sure your project is on the allow list.
    // Possible values are "base" and "nmt"
    model: model,
  };

  // Translates the text into the target language. "text" can be a string for
  // translating a single piece of text, or an array of strings for translating
  // multiple texts.
  let [translations] = await translate.translate(text, options);
  translations = Array.isArray(translations) ? translations : [translations];
  console.log('Translations:');
  translations.forEach((translation, i) => {
    console.log(`${text[i]} => (${target}) ${translation}`);
  });
}

translateTextWithModel();

PHP

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용PHP 설정 안내를 따르세요. 자세한 내용은 Cloud Translation PHP API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Translate\TranslateClient;

/**
 * @param string $text The text to translate.
 * @param string $targetLanguage Language to translate to.
 */
function translate_with_model(string $text, string $targetLanguage): void
{
    $model = 'nmt';  // "base" for standard edition, "nmt" for premium
    $translate = new TranslateClient();
    $result = $translate->translate($text, [
        'target' => $targetLanguage,
        'model' => $model,
    ]);
    print("Source language: $result[source]\n");
    print("Translation: $result[text]\n");
    print("Model: $result[model]\n");
}

Python

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Python API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def translate_text_with_model(target: str, text: str, model: str = "nmt") -> dict:
    """Translates text into the target language.

    Make sure your project is allowlisted.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, bytes):
        text = text.decode("utf-8")

    # 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.translate(text, target_language=target, model=model)

    print("Text: {}".format(result["input"]))
    print("Translation: {}".format(result["translatedText"]))
    print("Detected source language: {}".format(result["detectedSourceLanguage"]))

    return result

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.