I am trying to translate the field Short description to English since some of the rows are not in English. But using the code below I am not able to translate. The translate column and the original columns look exactly the same. Please see the image attached for the output.
from googletrans import Translator
translator = Translator()
mask = data['Short description'] !='en'
data['Short description_translated'] = data['Short description']
f = lambda x: translator.translate(x, dest='en').text
data.loc[mask, 'Short description_translated'] = data.loc[mask, 'Short description'].apply(f)
print (data)
The googletrans API that you are using is the same service as translate.google.com. Googletrans does not use the official Google Translation API. It uses the Google Translate Ajax API. You can use the Python client library or REST API provided in Google’s official Translation API. You can refer to the code mentioned below.
Using Python client library:
from os import environ
from google.cloud import translate
project_id = environ.get("PROJECT_ID", "")
assert project_id
parent = f"projects/{project_id}"
client = translate.TranslationServiceClient()
sample_text = "Bonjour"
target_language_code = "en"
response = client.translate_text(
contents=[sample_text],
target_language_code=target_language_code,
parent=parent,
)
for translation in response.translations:
print(translation.translated_text)
Using REST API:
Create a request.json file and use the below curl command mentioned.
request.json
{
"q": ["Bonjour", "Merci"],
"target": "en"
}
Curl Command
curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-
access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/language/translate/v2