Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
translate a srt file with google translate
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys,json,urllib
from pysrt import SubRipFile, SubRipItem
url_string = ''
def detect(text):
query = dict(v='1.0', q=text)
file = urllib.urlopen(url_string+'detect?%s' % urllib.urlencode(query))
result = json.loads(
return result['responseData']['language'] if result['responseData'] else None
def translate(text, input_language, output_language):
source = detect(text)
target = [input_language, output_language][source == input_language]
query = dict(v='1.0', q=text,langpair = '%s|%s' % (source, target))
file = urllib.urlopen(url_string+'translate?%s' % urllib.urlencode(query))
result = json.loads(
return result['responseData']['translatedText'] if result['responseData'] else None
def translate_srt_file(input_file, output_file, input_language, output_language):
"""translate a srt file from a language to another"""
print 'processing file', input_file
subs =
for sentence in subs:
sentence.text = translate(sentence.text, input_language, output_language) + '\n', 'utf-8')
def main():
if len(sys.argv) < 4:
info = '''
translate a subtitle file from a language to another.
Most of the code to use google translate API was taken there :
usage: input_file output_file input_language output_language
example: ./ ./ en fr
print info
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment