DEV Community

Cover image for Translate with the snake (Python)

Posted on

Translate with the snake (Python)

There are some sites that offer language translation. You may know Google translate which is one of them.

Did you know you can use those sites from Python code? Welcome to the jungle!

To do so you need the modules requests and BeautifulSoup. These modules are used to make the web request and fetch data. The example code below translate a string from English to French.

import requests
from bs4 import BeautifulSoup

def getHTMLText(url):
        r = requests.get(url, timeout=30)
        return r.text
        print("Get HTML Failed!")
        return 0

def google_translate(to_translate, from_language="en", to_language="fr"):
    base_url = "{}&sl={}&ie=UTF-8&q={}"
    url = base_url.format(to_language, from_language, to_translate)

    html = getHTMLText(url)
    if html:
        soup = BeautifulSoup(html, "html.parser")

        result = soup.find_all("div", {"class":"t0"})[0].text
        print("Translation Failed!")
        result = ""

    return result

if __name__ == '__main__':
    print(google_translate("Hello World!"))

The important part here is the last line, a function call to google_translate with the text to translate as parameter.

If you run it:

Bonjour le monde!

Related links:

Top comments (0)