Google Translate API: Enable word conversion

998 Views Asked by At

I'm translating a list of words using google translate API, however I noticed that for words that it cannot translate, it returns the same word in the source language.

For example, let's observe the following request of word array conversion from English to Hebrew:

const response = await axios.post<TranslateResponse>(`https://translation.googleapis.com/language/translate/v2?key=xxxxxxx`,
            {
                "q": ["SUNFINSH", "DOG"],
                "source": "en",
                "target": "he",
                "format": "text"
            });

The returned object is

{"data":{"translations":[{"translatedText":"SUNFINSH"},{"translatedText":"כֶּלֶב"}]}}

in the above example, you can see it translated "DOG", but could not translate "SUNFISH".

However, if I go to translate.google.com, and type in "SUNFISH", even though it does not translate it on the right panel UI, it does offer kind of a "literal" translation, as if it can simply convert the word to how it sounds in Hebrew.

Sunfish Translation Example

The question is, how can I get the same result using the Google Translate API?

1

There are 1 best solutions below

0
On BEST ANSWER

You may try and change "SUNFISH" into "sunfish" and it will return the expected output same as the screenshot you provided using the Google Translate UI.

As seen in the screenshot provided using the Google Translate UI, Google converted "SUNFISH" into "sunfish" first and then from there, it translated it to Hebrew.

Please see the screenshot of my testing. enter image description here

I also tested using "Sunfish" and still got the expected result in hebrew.

In addition, as mentioned in this official google support forum,

Google Translate must be case sensitive as no two languages follow the same Capitalization rule.

Below is my sample code used in testing for your reference.

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate').v2;

// Creates a client
const translate = new Translate();

 const text = ['sunfish', 'DOG'];
 const target = 'he';

async function translateText() {
  // 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, target);
  translations = Array.isArray(translations) ? translations : [translations];
  console.log('Translations:');
  translations.forEach((translation, i) => {
    console.log(`${text[i]} => (${target}) ${translation}`);
  });
}

translateText();