Skip to content

Instantly share code, notes, and snippets.

@nullren
Created March 24, 2013 07:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nullren/5230939 to your computer and use it in GitHub Desktop.
Save nullren/5230939 to your computer and use it in GitHub Desktop.
python script to translate my chinese srt files into english!
#!/usr/bin/python3
import sys
import re
import json
import html.parser
import urllib.parse as p
import urllib.request as r
def prnt(str):
print(str, end="")
def openfile():
file = sys.argv[1]
try:
return open(file, "r")
except:
print("failed to open %s." % file)
sys.exit(1)
is_frame = re.compile("^\d+$")
is_empty = re.compile("^$")
is_time = re.compile("^\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+$")
def subtext(line):
f = is_frame.match(line)
t = is_time.match(line)
e = is_empty.match(line)
return not (f or e or t)
API_KEY="GETYOUROWN"
def translate(line):
url = "https://www.googleapis.com/language/translate/v2?"
data = p.urlencode({ "key": API_KEY
, "q": line
, "source": "zh"
, "target": "en"
})
f = r.urlopen(url + data)
c = f.read().decode()
f.close()
j = json.loads(c)
t = j['data']['translations'][0]['translatedText']
g = html.parser.HTMLParser().unescape(t)
return g
for line in openfile():
if subtext(line):
prnt(translate(line) + "\n")
else:
prnt(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment