Home » how to translate text to various languages in Python

how to translate text to various languages in Python

Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification
Spring Framework Basics Video Course
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription

The ability to translate from one language to another is very useful functionality you can have in your application or script.

One of the most popular, if not the most popular is google translate. In this article we will look at a python

Table of Contents

Features

Googletrans is a free and unlimited python library that implemented Google Translate API. This uses the Google Translate Ajax API to make calls to such methods as detect and translate.

  • Fast and reliable – it uses the same servers that translate.google.com uses
  • Auto language detection
  • Bulk translations
  • Customizable service URL
  • HTTP/2 support

There are some important notes you should pay attention to

  • The maximum character limit on a single text is 15k.
  • Due to limitations of the web version of google translate, this API does not guarantee that the library would work properly at all times
  • Important: If you want to use a stable API, I highly recommend you to use Google’s official translate API.
  • If you get HTTP 5xx error , it’s probably because Google has banned your client IP address.

Installation

pip install googletrans
from googletrans import Translator

translator = Translator()

Note that Translator class has several optional arguments:

  • service_urls: This should be a list of strings that are the URLs of google translate API.
  • user_agent: A string that will be included in User-Agent header in the request.
  • proxies (dictionary): A Python dictionary that maps protocol or protocol and host to the URL of the proxy.
  • timeout: The timeout of each request you make, expressed in seconds.

 

Code

List supported languages

 

#!/usr/bin/env python

import googletrans

print(googletrans.LANGUAGES)

Specifing the source and the destination languages.

#!/usr/bin/env python

from googletrans import Translator

translator = Translator()

translated = translator.translate('hello world', src='en', dest='es')

print(translated.text)

and another

#!/usr/bin/env python

from googletrans import Translator

translator = Translator()
default = translator.translate('Lang niet gezien')
text1 = translator.translate('Lang niet gezien', src='nl', dest='de')
text2 = translator.translate('Lang niet gezien', src='nl', dest='es')
print(default.text)
print(text1.text)
print(text2.text)

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More