Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GoogleTranslate.py -> Sample object to translate text or html with Google Cloud using Python | Stratton Apps SL
# Author: Stratton Apps SL | andorrainsiders.com & strattonapps.com
from google.cloud import translate
import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'credentials.json'
proj_id = 'translate-33434'
class Session(object):
def __init__(self):
self.client = translate.TranslationServiceClient()
def translate(self,from_language, target_language, text ):
project_id = proj_id
contents = [text]
parent = self.client.location_path(project_id, "global")
response = self.client.translate_text(
parent=parent,
contents=contents,
mime_type='text/plain', # mime types: text/plain, text/html
source_language_code=from_language,
target_language_code=target_language)
return response.translations[0].translated_text.replace("\%","%")
#Example
translator = Session()
text = translator.translate("en","es","Andorra, a little country in the Pyrenees situated between Spain and France. This country has a highly attractive tax system for both companies and individuals.")
print(text)
"Andorra, un pequeño país de los Pirineos situado entre España y Francia. Este país tiene un sistema fiscal muy atractivo tanto para las empresas como para los individuos."
text = translator.translate("en","ca","Andorra, a little country in the Pyrenees situated between Spain and France. This country has a highly attractive tax system for both companies and individuals.")
print(text)
"Andorra, un petit país dels Pirineus situat entre Espanya i França. Aquest país té un sistema fiscal molt atractiu tant per a les empreses com per als individus."
@DiMiTriFrog
Copy link
Author

DiMiTriFrog commented Apr 10, 2020

I'm using this object to translate all articles, all words and slugs of andorrainsiders.com.
The Google Cloud Translate works better than expected, you can check live results in Andorra Insiders

@SalvaTerol
Copy link

This code is amazing. He saved my life when I was lost and the translations are great. Thank you!

@Paiolus
Copy link

Paiolus commented Apr 10, 2020

Thank you for sharing the code, that's just what I was looking for! Neither StackOverflow nor with a Google search i found a Google Cloud translate script, and here it is. This worked for me.

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