Traduire du texte avec UrlLib, BeautifulSoup et Google Translation

Salut les hommes,

Qui n’a  jamais voulu traduire un peu de texte automatiquement ? Des mots ou des phrase entières. On peut faire ça assez facilement avec UrlLib et BeautifulSoup.

Ouvrez un fichier test.py et collez-y le code suivant. Il faut avoir installé BeautifullSoup auparavant (easy_install BeautifulSoup ou pip install BeautifulSoup)

import urllib
import urllib2
from BeautifulSoup import BeautifulSoup
 
# texte à traduire
text = 'Respect my authority!'
 
# on créé les headers
headers = { 'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1',
'Referer': 'http://translate.google.com/'
}
 
# la langue originale du texte à traduire
lg_from = 'en'
 
# la langue dans laquelle on veut traduire l'article
lg_to = 'fr'
 
# Paramètres à passer en POST
params = urllib.urlencode( {'hl': 'fr',
'ie': 'UTF8',
'text': text.encode('utf-8'),
'sl': lg_from,
'tl': lg_to}
)
 
# On formule la requête
request = urllib2.Request("http://translate.google.com/translate_t?" + urllib.urlencode({'sl': lg_from, 'tl': lg_to}), None, headers)
html = urllib2.urlopen(request, params).read()
 
# on récupère la traduction avec BeautifulSoup
translated_soup = BeautifulSoup(html)
print translated_soup('span', id='result_box')[0].text

Exécutons le code…

$python test.py
Respectez mon autorité!

Attention toutefois Google n’authorise pas l’automation de ce genre de tâche sans passer par son API (payante).

No related posts.

flattr this!

One comment

  1. prout

Flux RSS des commentaires

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Jouer à mario en attendant que les autres répondent