From 4da92ede22e869a9ae23f039f11d47a705f04b4b Mon Sep 17 00:00:00 2001 From: Mike Hiretsky Date: Fri, 28 May 2010 14:10:10 +0400 Subject: [PATCH] Fix functions of convertation between string, dictionary and list --- pym/cl_utils.py | 135 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 107 insertions(+), 28 deletions(-) diff --git a/pym/cl_utils.py b/pym/cl_utils.py index 83fd78d..976400e 100644 --- a/pym/cl_utils.py +++ b/pym/cl_utils.py @@ -23,6 +23,7 @@ import subprocess import stat from shutil import copytree, rmtree import ctypes +import cl_overriding class _error: # Здесь ошибки, если они есть @@ -200,50 +201,128 @@ def getpathenv(): lpath=npath+lpath return ":".join(lpath) -def list2str(list): - '''Функция переводит список в строку''' - return '['+','.join(list)+']' +class MultiReplace: + """MultiReplace function object + + Usage: + replacer = MultiReplace({'str':'efg','in':'asd'}) + s = replacer("string") + """ + def __init__(self, repl_dict): + # string to string mapping; use a regular expression + keys = repl_dict.keys() + keys.sort(reverse=True) # lexical order + pattern = u"|".join([re.escape(key) for key in keys]) + self.pattern = re.compile(pattern) + self.dict = repl_dict + + def replace(self, s): + # apply replacement dictionary to string + def repl(match, get=self.dict.get): + item = match.group(0) + return get(item, item) + return self.pattern.sub(repl, s) + __call__ = replace + +def str2dict(s): + """Convert string to dictionary: + + String format: + {'key1':'value1','key2':'val\'ue2'} + """ + value = r'(?:\\\\|\\\'|[^\'])' + pair = r""" + \s*' # begin key + (%(v)s*) + ' # end key + \s*:\s* # delimeter key/value + ' # begin value + (%(v)s*) + '\s* # end value + """ % {"v":value} + reDict = re.compile(pair, re.X) + reMatchDict = re.compile(""" + ^{ # begin dict + ((%(v)s,)* # many pair with comma at end + %(v)s)? # pair without comma + }$ # end dict + """ % {'v':pair}, re.X) + if reMatchDict.match(s.strip()): + d = dict(reDict.findall(s)) + replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''}) + for i in d.keys(): + d[i] = replaceSlash(d[i]) + return d + else: + print _("wrong dict value: %s"%s) + cl_overriding.exit(1) def str2list(s): - '''Функция переводит строку в список''' - return s[1:-1].split(',') + """Convert string to list: -def dict2str(dict): - '''Функция перводит словарь в строку''' - return '{'+','.join(["%s:%s" % (str(k),str(v)) \ - for (k,v) in dict.items()])+'}' #: + String format: + ['value1','val\'ue2'] + """ + value = r'(?:\\\\|\\\'|[^\'])' + element = r""" + \s*' # begin value + (%(v)s*) + '\s* # end value + """ % {"v":value} + reList = re.compile(element, re.X) + reMatchList = re.compile(""" + ^\[ # begin dict + ((%(v)s,)* # many elements with comma at end + %(v)s)? # element without comma + \]$ # end dict + """ % {'v':element}, re.X) + if reMatchList.match(s.strip()): + replaceSlash = MultiReplace({'\\\\':'\\','\\\'':'\''}) + return [replaceSlash(i) for i in reList.findall(s)] + else: + print _("wrong list value: %s"%s) + cl_overriding.exit(1) -def str2dict(s): - '''Функция переводит строку в словарь''' - dict = {} - for i in s[1:-1].split(','): - k,v = i.split(':') - dict[k] = v - return dict +def list2str(list): + """Convert list to string + + Return string with escaped \ and '. + """ + replaceSlash = MultiReplace({'\\':'\\\\','\'':'\\\''}) + return "[%s]" % ','.join(["'%s'"%replaceSlash(str(i)) + for i in list ]) + +def dict2str(dict): + """Convert dictionry to string + + Return string with escaped \ and '. + """ + replaceSlash = MultiReplace({'\\':'\\\\','\'':'\\\''}) + return '{%s}' % ','.join(["'%s':'%s'" % (str(k),replaceSlash(str(v))) \ + for (k,v) in dict.items()]) def convertStrListDict(val): - '''Функция определеяется что на входе (строка, список, словарь) - и переводит их в строку и обратно''' - # если подан список + """Convert data between string, list, dict""" + # if val is list if type(val) == types.ListType: return list2str(val) - # если подан словарь + # if val is dictionary elif type(val) == types.DictType: return dict2str(val) - # если подана строка + # else it is string else: - # если поданная строка содержит словарь - if ':' in val and '{' in val: + # detect dictionary + if re.match("^{.*}$",val): return str2dict(val) - # если поданная строка содержит список - elif ',' in val and '[' in val: + # detect list + elif re.match("^[.*]$",val): return str2list(val) - # если это просто строка + # else is simple string else: return val def _toUNICODE(val): - """перевод текста в юникод""" + """Convert text to unicode""" if type(val) == types.UnicodeType: return val else: @@ -310,4 +389,4 @@ def copyDir(srcDir, destDir): def removeDir(rmDir): """Рекурсивное удаление директории""" rmtree(rmDir) - return True \ No newline at end of file + return True