Skip to content

Instantly share code, notes, and snippets.

@DiMiTriFrog
Created April 10, 2020 17:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DiMiTriFrog/157ea281c03b3534506cea69cee73dd3 to your computer and use it in GitHub Desktop.
Save DiMiTriFrog/157ea281c03b3534506cea69cee73dd3 to your computer and use it in GitHub Desktop.
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."
@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