-
-
Save ozero/59e2483d02a9c7918a8a076ced40d463 to your computer and use it in GitHub Desktop.
Machine Translation of .po files with Google Translate
This file contains 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
#### Requires #### | |
# goslate==1.3.0 | |
# polib==1.0.5 | |
#### / #### | |
import os, sys | |
import goslate | |
import argparse | |
import polib | |
import time | |
import datetime | |
import pprint | |
import shutil | |
# cli example: | |
# python translate.py --inpath=src/a0.po --outpath=ext/a0.po --lang=ja --whoami=myname@gmail.com | |
# Designed to don't break original po file (include comments etc) | |
parser = argparse.ArgumentParser(description="Machine Translation of Django's PO Files") | |
parser.add_argument('--inpath', help="Path to the INPUT po file", required=True) | |
parser.add_argument('--outpath', help="Path to the OUTPUT po file", required=True) | |
parser.add_argument('--lang', help="Destination language ISO-3166-2alpha code", required=True) | |
parser.add_argument('--whoami', help="Your email address", default="you@example.com") | |
args = parser.parse_args() | |
gs = goslate.Goslate() | |
input_file = polib.pofile(args.inpath) | |
time.sleep(1) | |
# build translation | |
c=0 | |
translated = [] | |
for entry in input_file: | |
##pprint.pprint ([entry.msgid]) | |
translated.append( [ | |
str(entry.msgid), | |
str(gs.translate(entry.msgid, args.lang)) | |
]) | |
time.sleep(1) | |
c += 1 | |
# make output | |
if os.path.exists(args.outpath): | |
os.remove(args.outpath) | |
# replace output | |
fr = open(args.inpath,'r') | |
fw = open(args.outpath,'w') | |
r = 0 | |
is_body = 0 | |
for row in fr: | |
inline = row.strip() | |
print (inline) | |
if inline == '': | |
is_body += 1 | |
if inline == 'msgstr ""': | |
if is_body == 0: | |
# write other lines | |
fw.write(inline + "\n") | |
else: | |
# write translation | |
fw.write('msgstr "' + translated[r][1].replace('"', '\\"') + '"' + "\n") | |
r += 1 | |
else: | |
# write other lines | |
fw.write(inline + "\n") | |
fr.close() | |
fw.close() | |
print ("Done. Translated %s messages" % c) | |
Author
ozero
commented
Aug 29, 2019
•
- Update syntax for Python 3
- Designed to don't break original po file (include comments etc)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment