使用 Cloud Translation 高级版 (v3) 翻译输入的文本。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
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"
)
// translateText translates input text and returns translated text.
func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error {
// projectID := "my-project-id"
// sourceLang := "en-US"
// targetLang := "fr"
// text := "Text you wish to translate"
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/global", projectID),
SourceLanguageCode: sourceLang,
TargetLanguageCode: targetLang,
MimeType: "text/plain", // Mime types: "text/plain", "text/html"
Contents: []string{text},
}
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.GetTranslations() {
fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
}
return nil
}
Java
在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Translation Java API 参考文档。
// Imports the Google Cloud Translation library.
import com.google.cloud.translate.v3.LocationName;
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 TranslateText {
// Set and pass variables to overloaded translateText() method for translation.
public static void translateText() 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 targetLanguage = "your-target-language";
String text = "your-text";
translateText(projectId, targetLanguage, text);
}
// Translate text to target language.
public static void translateText(String projectId, String targetLanguage, String text)
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, "global");
// Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
TranslateTextRequest request =
TranslateTextRequest.newBuilder()
.setParent(parent.toString())
.setMimeType("text/plain")
.setTargetLanguageCode(targetLanguage)
.addContents(text)
.build();
TranslateTextResponse response = client.translateText(request);
// Display the translation for each input text provided
for (Translation translation : response.getTranslationsList()) {
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 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 translateText() {
// Construct request
const request = {
parent: `projects/${projectId}/locations/${location}`,
contents: [text],
mimeType: 'text/plain', // mime types: text/plain, text/html
sourceLanguageCode: 'en',
targetLanguageCode: 'sr-Latn',
};
// Run request
const [response] = await translationClient.translateText(request);
for (const translation of response.translations) {
console.log(`Translation: ${translation.translatedText}`);
}
}
translateText();
PHP
在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 PHP 设置说明进行操作。如需了解详情,请参阅 Translation PHP API 参考文档。
use Google\Cloud\Translate\V3\TranslationServiceClient;
$translationServiceClient = new TranslationServiceClient();
/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $targetLanguage = 'fr';
// $projectId = '[Google Cloud Project ID]';
$contents = [$text];
$formattedParent = $translationServiceClient->locationName($projectId, 'global');
try {
$response = $translationServiceClient->translateText(
$contents,
$targetLanguage,
$formattedParent
);
// Display the translation for each input text provided
foreach ($response->getTranslations() as $translation) {
printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
}
} finally {
$translationServiceClient->close();
}
Python
在试用此示例之前,请按照《Translation 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Translation Python API 参考文档。
# Imports the Google Cloud Translation library
from google.cloud import translate
# Initialize Translation client
def translate_text(text="YOUR_TEXT_TO_TRANSLATE", project_id="YOUR_PROJECT_ID"):
"""Translating Text."""
client = translate.TranslationServiceClient()
location = "global"
parent = f"projects/{project_id}/locations/{location}"
# Translate text from English to French
# Detail on supported types can be found here:
# https://cloud.google.com/translate/docs/supported-formats
response = client.translate_text(
request={
"parent": parent,
"contents": [text],
"mime_type": "text/plain", # mime types: text/plain, text/html
"source_language_code": "en-US",
"target_language_code": "fr",
}
)
# Display the translation for each input text provided
for translation in response.translations:
print("Translated text: {}".format(translation.translated_text))
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。