| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
""" |
| 5 |
use a PO file to localize some expressions in a LaTeX file |
| 6 |
""" |
| 7 |
|
| 8 |
import sys, re |
| 9 |
|
| 10 |
gatherPattern = re.compile('^"(.*)"$') |
| 11 |
msgidPattern = re.compile('^msgid "(.*)"$') |
| 12 |
msgstrPattern = re.compile('^msgstr "(.*)"$') |
| 13 |
macroPattern = re.compile(r'(\\menuitem{)([^}]*)(})') |
| 14 |
|
| 15 |
class Localizer: |
| 16 |
def __init__(self, pofile): |
| 17 |
""" |
| 18 |
the constructor |
| 19 |
@param pofile a path to a PO file |
| 20 |
""" |
| 21 |
lines=open(pofile,'r').readlines() |
| 22 |
self.dic={} |
| 23 |
idGathering=False |
| 24 |
msgGathering=True |
| 25 |
ident="" |
| 26 |
msg="" |
| 27 |
for l in lines: |
| 28 |
m=msgidPattern.match(l) |
| 29 |
if m: |
| 30 |
idGathering=True |
| 31 |
if msgGathering: |
| 32 |
self.dic[ident]=msg |
| 33 |
msgGathering=False |
| 34 |
ident=m.group(1) |
| 35 |
continue |
| 36 |
m=msgstrPattern.match(l) |
| 37 |
if m: |
| 38 |
idGathering=False |
| 39 |
msgGathering=True |
| 40 |
msg=m.group(1) |
| 41 |
m=gatherPattern.match(l) |
| 42 |
if m: |
| 43 |
if idGathering: |
| 44 |
ident+=m.group(1) |
| 45 |
continue |
| 46 |
elif msgGathering: |
| 47 |
msg += m.group(1) |
| 48 |
continue |
| 49 |
#end of file; recording the last l10n |
| 50 |
self.dic[ident]=msg |
| 51 |
return |
| 52 |
|
| 53 |
def localize(self, lines): |
| 54 |
""" |
| 55 |
replaces strings to be localized |
| 56 |
@param lines a list of lines to be localized |
| 57 |
@return a list of localized lines |
| 58 |
""" |
| 59 |
return [re.sub(macroPattern, self.localizeFunc, l) for l in lines] |
| 60 |
|
| 61 |
def localizeFunc(self, matchObj): |
| 62 |
""" |
| 63 |
the true localizing function. |
| 64 |
@param matchObj a regular expression match object |
| 65 |
@return the replacement string |
| 66 |
""" |
| 67 |
ident=matchObj.group(2) |
| 68 |
if ident in self.dic: |
| 69 |
msg=self.dic[ident].decode("UTF-8").encode("ISO8859-1") |
| 70 |
return matchObj.group(1)+msg+matchObj.group(3) |
| 71 |
else: |
| 72 |
return matchObj.group(0) |
| 73 |
|
| 74 |
|
| 75 |
def usage(): |
| 76 |
""" |
| 77 |
prints a short message about the usage of the program |
| 78 |
""" |
| 79 |
print ("Usage: %s <LaTeXfile> <POfile>" %sys.argv[0]) |
| 80 |
sys.exit(1) |
| 81 |
|
| 82 |
if __name__ == '__main__': |
| 83 |
try: |
| 84 |
texfile=sys.argv[1] |
| 85 |
pofile=sys.argv[2] |
| 86 |
except: |
| 87 |
usage() |
| 88 |
|
| 89 |
l = Localizer(pofile) |
| 90 |
#print l.dic |
| 91 |
lines=open(texfile,'r').readlines() |
| 92 |
for line in l.localize(lines): |
| 93 |
sys.stdout.write(line) |
| 94 |
|