Skip to content

Instantly share code, notes, and snippets.

@ptbrowne
Last active August 28, 2017 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptbrowne/da23e17efdd5a7ca9626e650e0a00856 to your computer and use it in GitHub Desktop.
Save ptbrowne/da23e17efdd5a7ca9626e650e0a00856 to your computer and use it in GitHub Desktop.
easy_i18n.py

You have a translation file full of English. You want to translate it to French easily.

1. Output all translation strings

python easy_i18n.py en.json output

2. Copy those strings into Google Translate

3. Copy the output of Google Translate into a file

Let's call the file translated.txt

python easy_i18n.py en.json merge translated.txt > 

It outputs the fr.json file.

Check the output well since the tool is very simple and may have errors.

import json
def read_leaves(filename):
with open(filename) as f:
leaves = [t.strip() for t in f.readlines()]
return leaves
def merge_leaves(data, leaves):
counter = [0] # Have it into an array for scoping reasons
def _merge_leaves(data, leaves):
for k, v in data.iteritems():
if hasattr(v, 'keys'):
_merge_leaves(v, leaves)
else:
data[k] = leaves[counter[0]]
counter[0] += 1
_merge_leaves(data, leaves)
def print_leaves(data):
for k, v in data.iteritems():
if hasattr(v, 'keys'):
print_leaves(v)
else:
print v.encode('utf-8')
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('translation_file')
parser.add_argument('mode')
parser.add_argument('translations', nargs='?')
args = parser.parse_args()
with open(args.translation_file) as f:
data = json.load(f)
if args.mode == 'output':
print_leaves(data)
elif args.mode == 'merge':
leaves = read_leaves(args.translations)
merge_leaves(data, leaves)
print json.dumps(data, indent=2)
else:
print 'Unknown mode'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment