Translate strings (Basic edition)
Stay organized with collections
Save and categorize content based on your preferences.
Demonstrates translating strings by using Cloud Translation - Basic (v2).
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[],[],null,["# Translate strings (Basic edition)\n\nDemonstrates translating strings by using Cloud Translation - Basic (v2).\n\nCode sample\n-----------\n\n### Go\n\n\nBefore trying this sample, follow the Go setup instructions in the\n[Cloud Translation quickstart using\nclient libraries](/translate/docs/quickstart-client-libraries).\n\n\nFor more information, see the\n[Cloud Translation Go API\nreference documentation](https://godoc.org/cloud.google.com/go/translate).\n\n\nTo authenticate to Cloud Translation, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import (\n \t\"context\"\n \t\"fmt\"\n\n \t\"cloud.google.com/go/translate\"\n \t\"golang.org/x/text/language\"\n )\n\n func translateTextWithModel(targetLanguage, text, model string) (string, error) {\n \t// targetLanguage := \"ja\"\n \t// text := \"The Go Gopher is cute\"\n \t// model := \"nmt\"\n\n \tctx := context.Background()\n\n \tlang, err := language.Parse(targetLanguage)\n \tif err != nil {\n \t\treturn \"\", fmt.Errorf(\"language.Parse: %w\", err)\n \t}\n\n \tclient, err := translate.https://cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_Client_NewClient(ctx)\n \tif err != nil {\n \t\treturn \"\", fmt.Errorf(\"translate.NewClient: %w\", err)\n \t}\n \tdefer client.Close()\n\n \tresp, err := client.https://cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_Client_Translate(ctx, []string{text}, lang, &translate.https://cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_Options{\n \t\tModel: model, // Either \"nmt\" or \"base\".\n \t})\n \tif err != nil {\n \t\treturn \"\", fmt.Errorf(\"Translate: %w\", err)\n \t}\n \tif len(resp) == 0 {\n \t\treturn \"\", nil\n \t}\n \treturn resp[0].https://cloud.google.com/go/docs/reference/cloud.google.com/go/translate/latest/index.html#cloud_google_com_go_translate_HTML_Text, nil\n }\n\n### Java\n\n\nBefore trying this sample, follow the Java setup instructions in the\n[Cloud Translation quickstart using\nclient libraries](/translate/docs/quickstart-client-libraries).\n\n\nFor more information, see the\n[Cloud Translation Java API\nreference documentation](https://cloud.google.com/java/docs/reference/google-cloud-translate/latest/com.google.cloud.translate).\n\n\nTo authenticate to Cloud Translation, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n Translation translation =\n translate.translate(\n \"Hola Mundo!\",\n Translate.TranslateOption.sourceLanguage(\"es\"),\n Translate.TranslateOption.targetLanguage(\"de\"),\n // Use \"base\" for standard edition, \"nmt\" for the premium model.\n Translate.TranslateOption.model(\"nmt\"));\n\n System.out.printf(\"TranslatedText:\\nText: %s\\n\", translation.getTranslatedText());\n\n### Node.js\n\n\nBefore trying this sample, follow the Node.js setup instructions in the\n[Cloud Translation quickstart using\nclient libraries](/translate/docs/quickstart-client-libraries).\n\n\nFor more information, see the\n[Cloud Translation Node.js API\nreference documentation](/nodejs/docs/reference/translate/latest).\n\n\nTo authenticate to Cloud Translation, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // Imports the Google Cloud client library\n const {Translate} = require('https://cloud.google.com/nodejs/docs/reference/translate/latest/overview.html').v2;\n\n // Creates a client\n const translate = new https://cloud.google.com/nodejs/docs/reference/translate/latest/translate/v2.translate.html();\n\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // const text = 'The text to translate, e.g. Hello, world!';\n // const target = 'The target language, e.g. ru';\n // const model = 'The model to use, e.g. nmt';\n\n async function translateTextWithModel() {\n const options = {\n // The target language, e.g. \"ru\"\n to: target,\n // Make sure your project is on the allow list.\n // Possible values are \"base\" and \"nmt\"\n model: model,\n };\n\n // Translates the text into the target language. \"text\" can be a string for\n // translating a single piece of text, or an array of strings for translating\n // multiple texts.\n let [translations] = await https://cloud.google.com/nodejs/docs/reference/translate/latest/translate/v2.translate.html.https://cloud.google.com/nodejs/docs/reference/translate/latest/translate/v2.translate.html(text, options);\n translations = Array.isArray(translations) ? translations : [translations];\n console.log('Translations:');\n translations.forEach((translation, i) =\u003e {\n console.log(`${text[i]} =\u003e (${target}) ${translation}`);\n });\n }\n\n translateTextWithModel();\n\n### PHP\n\n\nBefore trying this sample, follow the PHP setup instructions in the\n[Cloud Translation quickstart using\nclient libraries](/translate/docs/quickstart-client-libraries).\n\n\nFor more information, see the\n[Cloud Translation PHP API\nreference documentation](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/latest/translate/readme).\n\n\nTo authenticate to Cloud Translation, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n use Google\\Cloud\\Translate\\TranslateClient;\n\n /**\n * @param string $text The text to translate.\n * @param string $targetLanguage Language to translate to.\n */\n function translate_with_model(string $text, string $targetLanguage): void\n {\n $model = 'nmt'; // \"base\" for standard edition, \"nmt\" for premium\n $translate = new TranslateClient();\n $result = $translate-\u003etranslate($text, [\n 'target' =\u003e $targetLanguage,\n 'model' =\u003e $model,\n ]);\n print(\"Source language: $result[source]\\n\");\n print(\"Translation: $result[text]\\n\");\n print(\"Model: $result[model]\\n\");\n }\n\n### Python\n\n\nBefore trying this sample, follow the Python setup instructions in the\n[Cloud Translation quickstart using\nclient libraries](/translate/docs/quickstart-client-libraries).\n\n\nFor more information, see the\n[Cloud Translation Python API\nreference documentation](/python/docs/reference/translate/latest).\n\n\nTo authenticate to Cloud Translation, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n def translate_text_with_model(target: str, text: str, model: str = \"nmt\") -\u003e dict:\n \"\"\"Translates text into the target language.\n\n Make sure your project is allowlisted.\n\n Target must be an ISO 639-1 language code.\n See https://g.co/cloud/translate/v2/translate-reference#supported_languages\n \"\"\"\n from google.cloud import translate_v2 as translate\n\n translate_client = translate.Client()\n\n if isinstance(text, bytes):\n text = text.decode(\"utf-8\")\n\n # Text can also be a sequence of strings, in which case this method\n # will return a sequence of results for each text.\n result = translate_client.translate(text, target_language=target, model=model)\n\n print(\"Text: {}\".format(result[\"input\"]))\n print(\"Translation: {}\".format(result[\"translatedText\"]))\n print(\"Detected source language: {}\".format(result[\"detectedSourceLanguage\"]))\n\n return result\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=translate)."]]