Last active
July 6, 2023 00:56
-
-
Save NimJay/61be5cc1e047eb1a887a85fa25b1d472 to your computer and use it in GitHub Desktop.
This Golang script translates a list of strings/phrases from one languages to another — using Google's translation API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"os" | |
"cloud.google.com/go/translate" | |
"golang.org/x/text/language" | |
) | |
// Running "go run translate-list-of-strings.go" will run this main() function. | |
func main() { | |
ctx := context.Background() | |
stringsToTranslate := []string{"Do you speak Spanish?", "Where is the bathroom?"} | |
fmt.Printf("Running translateListOfStrings().\n") | |
translations, err := translateListOfStrings(ctx, "es", stringsToTranslate) // "es" stands for Español/Spanish. | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Error from translateText(): %s\n", err) | |
} else { | |
fmt.Printf("Translations: %v\n", translations) | |
} | |
} | |
func translateListOfStrings( | |
ctx context.Context, targetLanguage string, stringsToTranslate []string, | |
) ([]string, error) { | |
// Get language.Tag of the target language. | |
lang, err := language.Parse(targetLanguage) | |
if err != nil { | |
return nil, fmt.Errorf("language.Parse: %w", err) | |
} | |
// Create a new client for the translate API. | |
fmt.Printf("Creating new client for the translate API.\n") | |
client, err := translate.NewClient(ctx) | |
if err != nil { | |
return nil, err | |
} | |
defer client.Close() // Ensure the client connection is eventually closed. | |
// Translate! | |
fmt.Printf("Translating via Translate API...\n") | |
response, err := client.Translate(ctx, stringsToTranslate, lang, nil) | |
if err != nil { | |
return nil, fmt.Errorf("Translate: %w", err) | |
} | |
if len(response) == 0 { | |
return nil, fmt.Errorf("Translate returned empty response to text.\n") | |
} | |
translations := make([]string, len(stringsToTranslate)) | |
for i := 0; i < len(stringsToTranslate); i++ { | |
translations[i] = response[i].Text | |
} | |
return translations, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run this script:
Learn more about Google's Translation API here.