#!/usr/bin/env python
# -*- coding: utf-8 -*-
import locale,os,sys
class i18n(object):
""" Internationalization class
"""
__instance = None
__loaded = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, fileName=None, dir_path=None, listLang=None, default=None):
""" Load the file and set the dict
"""
if self.__loaded:
return
self.__loaded = True
#List of possibles languages
if not listLang: listLang = ("en", "it", "fr", "de")
self.__listLang = listLang
self.__default = default or "en"
suffix = self.getLangCodeFirstTwo()
self.dictTranlaste = dict()
if not dir_path: dir_path = os.getcwd()
if not fileName: fileName = os.path.normpath(os.path.join(dir_path, "language_"))
if default is not None and default in listLang:
fileName += default
else:
fileName += suffix
self.fileName = fileName
for i in open(fileName, 'r').readlines():
i = i.strip()
#no comments
if i.startswith("#"): continue
values = i.split("=", 1)
if len(values) < 2: continue
key, value = values
value = value.strip().replace("\\t", "\t" ).replace("\\n", "\n" )
self.dictTranlaste[key.strip()] = value
def getList(self, key, separator=","):
""" Return a list of values, split by separator
"""
return [ x.strip() for x in self.getValue(key).split(separator) ]
def getValue(self, key):
""" Return the value for the key
"""
if key in self.dictTranlaste:
return self.dictTranlaste[key]
else:
return "No key"
def getLangCodeFirstTwo(self):
""" Return the lenguage code
"""
l = locale.getdefaultlocale()[0][:2]
if l in self.__listLang: return l
else: return self.__default
def getLangCode(self,):
""" Return the lenguage code
"""
return locale.getdefaultlocale()
def __call__(self, key):
""" Simple method for retrive the values
"""
return self.getValue(key)
|