DEV Community

loading...
Cover image for Translate with the snake (Python)

Translate with the snake (Python)

petercour
・1 min read

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.

#!/usr/bin/python3
import requests
from bs4 import BeautifulSoup

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

def google_translate(to_translate, from_language="en", to_language="fr"):
    base_url = "https://translate.google.com/m?hl={}&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")

    try:
        result = soup.find_all("div", {"class":"t0"})[0].text
    except:
        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:

python3 example.py
Bonjour le monde!

Related links:

Discussion (0)