📜 ⬆️ ⬇️

google translate script

Hello. All that is stated below is my first really useful (at least for me) experience of using python. I would be grateful if you tell me how to improve / optimize the script.



For a long time I had a script on a bash who translated everything through Google google that he was fed
translate 'test' en ru

I wanted him to give out possible alternatives, as Google recently learned. At the same time I decided to arrange a python practice :)
')

Here's what happened:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"" "This script allow users to translate a string
from one language to another with Google translate"
""

import sys
import re
import urllib
import urllib2
import json

def print_params(data):
"" "print parameters from list" ""
for val in data:
if isinstance(val, basestring):
print "\t " + val

def main():
"" "
Usage:
first arg - string to translate
second arg - source lang
third arg - target lang
Example:
translate.py 'text to translate' en ru
translate.py 'text to translate' ru en
"
""

url = "http://translate.google.com/translate_a/t?%s"
list_of_params = { 'client' : 't' ,
'hl' : 'en' ,
'multires' : '1' , }

#all arguments given
if len(sys.argv) == 4:
list_of_params.update({ 'text' : sys.argv[1],
'sl' : sys.argv[2],
'tl' : sys.argv[3] })

request = urllib2.Request(url % urllib.urlencode(list_of_params),
headers={ 'User-Agent' : 'Mozilla/5.0' , 'Accept-Charset' : 'utf-8' })
res = urllib2.urlopen(request).read()

fixed_json = re.sub(r ',{2,}' , ',' , res).replace( ',]' , ']' )
data = json.loads(fixed_json)

#simple translation
print "%s / %s / %s" % (data[0][0][0], data[0][0][1],
data[0][0][2] or data[0][0][3])

#abbreviation
if not isinstance(data[1], basestring):
print data[1][0][0]
print_params(data[1][0][1])

#interjection
try :
if not isinstance(data[1][1], basestring):
print data[1][1][0]
print_params(data[1][1][1])
except Exception:
print "no interjection"
else :
print main.__doc__

if __name__ == '__main__' :
main()


* This source code was highlighted with Source Code Highlighter .


Download script

PS
Thanks for the constructive comments. Updated code and file.
Gave an error if the phrase was like how are you? # fixed

Pps
Thank you all for the positive feedback and constructive criticism.
By request, wrote another version of the script, which translates through Google API v2. Unfortunately the API does not offer multiple meanings of a single word. Perhaps in the future this feature will be added.

To use the 2nd version of the script, you need to get the API key from the link code.google.com/apis/console/?api=translate and replace ***** in the script with your key.

Here is the actual script itself:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
"" "This script allow users to translate a string
from one language to another with Google Translate API
You have to insert Your Translate API key
Get your API key from here:
code.google.com/apis/console/?api=translate
Replace
api_key = '**********' with your API key
"
""

import sys
import urllib
import urllib2
import json

def translate(list_of_params):
"" "Translate given text" ""
url = "https://www.googleapis.com/language/translate/v2?%s"
request = urllib2.Request(url % urllib.urlencode(list_of_params),
headers={ 'User-Agent' : 'Mozilla/5.0' , 'Accept-Charset' : 'utf-8' })
res = urllib2.urlopen(request).read()
translated = json.loads(res)
for translations in translated[ 'data' ][ 'translations' ]: print translations[ 'translatedText' ]

def main():
"" "
Usage:
first arg - string to translate
second arg - source lang
third arg - target lang
Example:
translate.py 'text to translate' en ru
translate.py 'text to translate' ru en
translate.py 'auto detect source language' ru
"
""
api_key = '**********'
list_of_params = { 'key' : api_key, }

if len(sys.argv) == 4:
#both langs entered
list_of_params.update({ 'q' : sys.argv[1],
'source' : sys.argv[2],
'target' : sys.argv[3] })
translate(list_of_params)
elif len(sys.argv) == 3:
#auto source language
list_of_params.update({ 'q' : sys.argv[1],
'target' : sys.argv[2] })
translate(list_of_params)
else :
print main.__doc__

if __name__ == '__main__' :
main()

* This source code was highlighted with Source Code Highlighter .


Download script

Source: https://habr.com/ru/post/113243/


All Articles