📜 ⬆️ ⬇️

Writing a console translator for * nix in Python

Hello. Surely you met unfamiliar English words or phrases, and you constantly had to go into the browser, open a website with an online translator and translate, while thinking how good it would be if it were implemented as software under * nix.

Under Windows operating systems, there have been many translators for a long time, but for unix systems, personally, I have not yet met.

On your marks!


And so we begin, we will write in the programming language python. It is in almost all * nix systems.
To write a translator, we will need one library not included in the standard python set - simplejson. You can download it on the official website .
')
Once downloaded, you can either install into the system, or put the folder simplesjon located in the archive next to our executable python file.

Got simplejson? Now create the translate.py file and move from theory to practice.
You can program in anything, even in nano, but I prefer the editor Geany.

We should get this structure of the project:


We will not touch the library, so go to the file translate.py:
We import the libraries we need:
 #!/usr/bin/python # -*- coding: utf-8 -*- import httplib import urllib2 import simplejson as json import sys 
#!/usr/bin/python # -*- coding: utf-8 -*- import httplib import urllib2 import simplejson as json import sys

The most important and only function
 user_agent = 'Mozilla/5.0 (X11; U; Linux x86_64; ru; rv:1.9.0.4) Gecko/2008120916 Gentoo Firefox/3.0.4' #    User-Agent    def translate_handler(lang,body): body = ' '.join(body) if len(sys.argv)<2: print u'$ en/ru text'; return #     try: if lang=='ru': req = urllib2.Request(unicode(u'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s' % (urllib2.quote(body),u'en%7Cru')),'utf-8') #        ,     elif lang=='en': req = urllib2.Request(unicode(u'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s' % (urllib2.quote(body),u'ru%7Cen')),'utf-8') #      elif lang=='en': print str(unicode(body,'utf-8')) else: print u'Available languages: en, ru'; return req.add_header('User-Agent',user_agent) #     User-Agent reqf = urllib2.urlopen(req) #   except urllib2.HTTPError, e: print str(e) answ=json.load(reqf) #   json   if answ['responseStatus']!=200: print str(answ['responseStatus'])+': '+answ['responseDetails'] #           elif answ['responseData']: print answ['responseData']['translatedText'] else: print u'unknown error >_<' translate_handler(sys.argv[1],sys.argv[2:]) #   
user_agent = 'Mozilla/5.0 (X11; U; Linux x86_64; ru; rv:1.9.0.4) Gecko/2008120916 Gentoo Firefox/3.0.4' # User-Agent def translate_handler(lang,body): body = ' '.join(body) if len(sys.argv)<2: print u'$ en/ru text'; return # try: if lang=='ru': req = urllib2.Request(unicode(u'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s' % (urllib2.quote(body),u'en%7Cru')),'utf-8') # , elif lang=='en': req = urllib2.Request(unicode(u'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s' % (urllib2.quote(body),u'ru%7Cen')),'utf-8') # elif lang=='en': print str(unicode(body,'utf-8')) else: print u'Available languages: en, ru'; return req.add_header('User-Agent',user_agent) # User-Agent reqf = urllib2.urlopen(req) # except urllib2.HTTPError, e: print str(e) answ=json.load(reqf) # json if answ['responseStatus']!=200: print str(answ['responseStatus'])+': '+answ['responseDetails'] # elif answ['responseData']: print answ['responseData']['translatedText'] else: print u'unknown error >_<' translate_handler(sys.argv[1],sys.argv[2:]) #


Just in case, I will publish the whole code:

 #!/usr/bin/evn python # -*- coding: utf-8 -*- import httplib import urllib2 import simplejson as json import sys user_agent = 'Mozilla/5.0 (X11; U; Linux x86_64; ru; rv:1.9.0.4) Gecko/2008120916 Gentoo Firefox/3.0.4' def translate_handler(lang,body): body = ' '.join(body) if len(sys.argv)<2: print u'$ en/ru text'; return try: if lang=='ru': req = urllib2.Request(unicode(u'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s' % (urllib2.quote(body),u'en%7Cru')),'utf-8') elif lang=='en': req = urllib2.Request(unicode(u'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s' % (urllib2.quote(body),u'ru%7Cen')),'utf-8') elif lang=='en': print str(unicode(body,'utf-8')) else: print u'Available languages: en, ru'; return req.add_header('User-Agent',user_agent) reqf = urllib2.urlopen(req) except urllib2.HTTPError, e: print str(e) answ=json.load(reqf) if answ['responseStatus']!=200: print str(answ['responseStatus'])+': '+answ['responseDetails'] elif answ['responseData']: print answ['responseData']['translatedText'] else: print u'unknown error >_<' translate_handler(sys.argv[1],sys.argv[2:]) 
#!/usr/bin/evn python # -*- coding: utf-8 -*- import httplib import urllib2 import simplejson as json import sys user_agent = 'Mozilla/5.0 (X11; U; Linux x86_64; ru; rv:1.9.0.4) Gecko/2008120916 Gentoo Firefox/3.0.4' def translate_handler(lang,body): body = ' '.join(body) if len(sys.argv)<2: print u'$ en/ru text'; return try: if lang=='ru': req = urllib2.Request(unicode(u'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s' % (urllib2.quote(body),u'en%7Cru')),'utf-8') elif lang=='en': req = urllib2.Request(unicode(u'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s' % (urllib2.quote(body),u'ru%7Cen')),'utf-8') elif lang=='en': print str(unicode(body,'utf-8')) else: print u'Available languages: en, ru'; return req.add_header('User-Agent',user_agent) reqf = urllib2.urlopen(req) except urllib2.HTTPError, e: print str(e) answ=json.load(reqf) if answ['responseStatus']!=200: print str(answ['responseStatus'])+': '+answ['responseDetails'] elif answ['responseData']: print answ['responseData']['translatedText'] else: print u'unknown error >_<' translate_handler(sys.argv[1],sys.argv[2:])


At this development of the software is complete. You can check and run the file this way:
python translate.py en hello - will translate the text into English
python translate.py ru hello - will translate the text into Russian

“But this is not convenient,” you say. Indeed, typing such a large startup command in the console is really difficult.

Decision


Take the folder with the project and move it to some directory such as / usr / share
and we will have / usr / share / translate

Then in your BINDIR'e (on my debian - / usr / bin) we will create 2 files, en and ru:

The contents of the file / usr / bin / ru:

python /usr/share/translate/translate.py ru $$*
The contents of the / usr / bin / en file:

python /usr/share/translate/translate.py en $$*

Total:


Our system now has 2 new commands: en and ru, respectively.
Now it has become much more convenient to use: en text for translation or ru text for translation

You can still do this:
 ferym@ferym-desktop:~$ ping -c 3 ya.ru | xargs ru $* PING ya.ru (77.88.21.3) 56 (84)  . 64   www.yandex.ru (77.88.21.3): icmp_seq = 1 TTL = 60  = 6,20  64   www.yandex.ru (77.88.21.3): 2 = icmp_seq TTL = 60  = 4,10  64   www.yandex.ru (77.88.21.3): icmp_seq = 3 TTL = 60  = 3,78  --- ya.ru   --- 3 , , 3 , 0%  ,  2001ms RTT  /  /  / mdev = 3.787/4.698/6.207/1.074  


Minuses:

Virtually any program has its drawbacks: this one is the absence of a local database, the entire translation is carried out via the Internet. But in the age of Internet technologies, when the Internet is in every home - I think this is not a problem.

Thanks for attention.

UPD: I do not impose my opinion on anyone, I showed how I realized it

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


All Articles