Last active
August 29, 2015 14:01
-
-
Save Taehun/89e5c2b469fc91023d20 to your computer and use it in GitHub Desktop.
Python Google Translator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding:utf-8 -*- | |
# Usage: $echo "This is google translator." | python google_trans.py [-i <Input Language>] [-o <Output Language>] [-s] | |
import sys | |
from BeautifulSoup import BeautifulSoup | |
import urllib2 | |
import urllib | |
import re | |
import getopt | |
import os | |
def google_trans(in_str, in_lang, out_lang): | |
data = {'sl':in_lang,'tl':out_lang,'text': in_str} | |
querystring = urllib.urlencode(data) | |
request = urllib2.Request('http://www.translate.google.com' + '?' + querystring ) | |
request.add_header('User-Agent', 'Mozilla/5.0 (Linux; ko; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11') | |
opener = urllib2.build_opener() | |
feeddata = opener.open(request).read() | |
soup = BeautifulSoup(feeddata) | |
result = soup.find('span', id="result_box") | |
ret_str = re.sub('<[^<]+?>', '', str(result)) | |
return ret_str.replace(''', "'") | |
in_lang = 'en' | |
out_lang = 'ko' | |
sound = False | |
opts, _ = getopt.getopt(sys.argv[1:], 'i:o:s', ['input_lang=', 'output_lang=']) | |
for opt, arg in opts: | |
if opt in ('-i', '--input_lang'): | |
in_lang = arg | |
elif opt in ('-o', '--output_lang'): | |
out_lang = arg | |
elif opt == '-s': | |
sound = True | |
out_str = google_trans(sys.stdin.read().strip(), in_lang, out_lang) | |
print out_str | |
if sound: | |
os.system('wget -q -U Mozilla -O sound.mp3 "http://translate.google.com/translate_tts?ie=UTF-8&tl=' + out_lang + '&q=' + out_str + '"') | |
os.system('mplayer sound.mp3') | |
os.system('rm sound.mp3') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment