Google Translate

This is the place to post any code that you want to share with the community. Only completed scripts should be posted here.
Note: posts here are not necessarily endorsed by the community, and may represent amateur or even bad practices.

Google Translate

Postby wavic » Wed Aug 03, 2016 12:42 am

I was looking for web scrapping tutorials and I came across these slides:
http://www.slideshare.net/null0x00/intr ... -scrapping

I've found it useful and I want to share it. So I've did some changes as handling command line arguments and adding bs4 instead the old one. GUI can be implement easy.
It is intended for English/Bulgarian translation. Additional languages can be added easy. As variables or argparse the command line arguments for variety of languages.

url = 'http://translate.google.com/?sl=en&tl=bg&text='
sl = source language
tl = target language

Code: Select all
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
import sys


def main():
    url = 'http://translate.google.com/?sl=en&tl=bg&text='

    q = '+'.join(sys.argv[1:])

    full_url = '{}{}'.format(url, q)

    # for BeautifulSoup 3 uncoment this and coment the next one
    #soup = BeautifulSoup(requests.get(full_url).content,
    #                    convertEntities=BeautifulSoup.HTML_ENTITIES)

    soup = BeautifulSoup(requests.get(full_url).content, "lxml")

    print((soup.find('div', {'id': 'gt-res-content'}).find('span',
                        {'id': 'result_box'}).text))


if __name__ == '__main__':
    main()
wavic
 
Posts: 165
Joined: Wed May 25, 2016 8:51 pm

Re: Google Translate

Postby snippsat » Wed Aug 03, 2016 4:32 pm

Good ;)
Can do a little rewrite so that argument which is given to search string clearer,
and easier to change.
Code: Select all
import requests
from bs4 import BeautifulSoup

def translate
(from_lang,to_lang,trans):
    url = 'http://translate.google.com/?sl={}&tl={}&text={}'.\
                               format(from_lang,to_lang,trans)

    soup = BeautifulSoup(requests.get(url).content, "lxml")
    print((soup.find('div', id='gt-res-content').
             find('span', id='result_box').text))

if __name__ == '__main__':
    from_lang = 'en'
    to_lang = 'de'
    trans = 'Hello my car is red'
    translate(from_lang,to_lang,trans) #--> Hallo mein Auto ist rot   

TextBlob is cool :P
Code: Select all
>>> from textblob import TextBlob
>>> en_blob = TextBlob(u'Simple is better than complex.')
>>>
 en_blob.translate(to='de')
TextBlob("Einfach ist besser als kompliziert."


GUI can be implement easy.

Remember it did a GUI for this in WxPython,has to be 7-8 year ago.
Then was Google translate api free.
Looked like this.
Image
We will be moving to python-forum.io on October 1 2016
User avatar
snippsat
 
Posts: 1251
Joined: Thu Feb 21, 2013 12:04 am


Return to Completed Scripts

Who is online

Users browsing this forum: No registered users and 2 guests