Skip to content

Instantly share code, notes, and snippets.

@NimJay
Last active July 6, 2023 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NimJay/61be5cc1e047eb1a887a85fa25b1d472 to your computer and use it in GitHub Desktop.
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.
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
}
@NimJay
Copy link
Author

NimJay commented Jul 6, 2023

To run this script:

go mod init example.com/my-temporary-module-path  # Initialize your temporary module.
go get                                            # Download dependencies.
go run translate-list-of-strings.go               # Run the script!

Learn more about Google's Translation API here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment