Skip to content

Instantly share code, notes, and snippets.

@highfestiva
Created September 20, 2013 08:31
Show Gist options
  • Save highfestiva/6634748 to your computer and use it in GitHub Desktop.
Save highfestiva/6634748 to your computer and use it in GitHub Desktop.
Why not translate everything you print into Swedish? Translator stolen from this guy: https://github.com/terryyin/google-translate-python/blob/master/translate.py
import re
from urllib import request
from urllib.parse import quote
string_pattern = r"\"(([^\"\\]|\\.)*)\""
match_string = re.compile(
r"\,?\["
+ string_pattern + r"\,"
+ string_pattern + r"\,"
+ string_pattern + r"\,"
+ string_pattern
+r"\]")
def translate(text, from_lang, to_lang):
json5 = _get_json5_from_google(text, from_lang, to_lang)
return _unescape(_get_translation_from_json5(json5))
def _get_translation_from_json5(content):
result = ""
pos = 2
while True:
m = match_string.match(content, pos)
if not m:
break
result += m.group(1)
pos = m.end()
return result
def _get_json5_from_google(text, from_lang, to_lang):
escaped_source = quote(text, '')
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19'}
req = request.Request(
url="http://translate.google.com/translate_a/t?client=t&ie=UTF-8&oe=UTF-8"
+"&sl=%s&tl=%s&text=%s" % (from_lang, to_lang, escaped_source)
, headers = headers)
try:
proxyinit = open("proxyinit.py").read()
exec(proxyinit)
except:
pass
r = request.urlopen(req)
return r.read().decode('utf-8')
def _unescape(text):
return re.sub(r"\\.?", lambda x:eval('"%s"'%x.group(0)), text)
class translate_stdout:
def __init__(self, f):
self.f = f
def write(self, text):
self.f.write(translate(text, from_lang='en', to_lang='sv')+'\n')
def flush(self):
self.f.flush()
import sys
sys.stdout = translate_stdout(sys.stdout)
def main():
print('Python rocks and rolls!')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment