From 696bdc8ac538c7734d8baa0bd61abe18df53612e Mon Sep 17 00:00:00 2001 From: AICells <1713699517@qq.com> Date: Thu, 16 Jul 2020 15:38:01 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/color_print.py | 257 ++++++++------- src/decoder.py | 303 +++++++++--------- src/genCfgs.py | 109 +++---- .../slpp.py | 32 +- .../tests.py | 5 +- src/slpp/slpp.py | 32 +- src/slpp/tests.py | 5 +- src/writer.py | 27 +- src/writer_elixir.py | 255 ++++++++------- src/writer_erlang_erl.py | 196 ++++++----- src/writer_erlang_hrl.py | 138 ++++---- src/writer_json_array.py | 13 +- src/writer_json_object.py | 174 +++++----- src/writer_lua.py | 232 +++++++------- src/writer_python.py | 237 +++++++------- src/writer_xml.py | 107 ++++--- 16 files changed, 1066 insertions(+), 1056 deletions(-) diff --git a/src/color_print.py b/src/color_print.py index c4839f6..9acb0e0 100644 --- a/src/color_print.py +++ b/src/color_print.py @@ -5,215 +5,230 @@ import ctypes import sys - + STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 - + # 字体颜色定义 ,关键在于颜色编码,由2位十六进制组成,分别取0~f,前一位指的是背景色,后一位指的是字体色 -#由于该函数的限制,应该是只有这16种,可以前景色与背景色组合。也可以几种颜色通过或运算组合,组合后还是在这16种颜色中 +# 由于该函数的限制,应该是只有这16种,可以前景色与背景色组合。也可以几种颜色通过或运算组合,组合后还是在这16种颜色中 # Windows CMD命令行 字体颜色定义 text colors -FOREGROUND_BLACK = 0x00 # black. -FOREGROUND_DARKBLUE = 0x01 # dark blue. -FOREGROUND_DARKGREEN = 0x02 # dark green. -FOREGROUND_DARKSKYBLUE = 0x03 # dark skyblue. -FOREGROUND_DARKRED = 0x04 # dark red. -FOREGROUND_DARKPINK = 0x05 # dark pink. -FOREGROUND_DARKYELLOW = 0x06 # dark yellow. -FOREGROUND_DARKWHITE = 0x07 # dark white. -FOREGROUND_DARKGRAY = 0x08 # dark gray. -FOREGROUND_BLUE = 0x09 # blue. -FOREGROUND_GREEN = 0x0a # green. -FOREGROUND_SKYBLUE = 0x0b # skyblue. -FOREGROUND_RED = 0x0c # red. -FOREGROUND_PINK = 0x0d # pink. -FOREGROUND_YELLOW = 0x0e # yellow. -FOREGROUND_WHITE = 0x0f # white. - - +FOREGROUND_BLACK = 0x00 # black. +FOREGROUND_DARKBLUE = 0x01 # dark blue. +FOREGROUND_DARKGREEN = 0x02 # dark green. +FOREGROUND_DARKSKYBLUE = 0x03 # dark skyblue. +FOREGROUND_DARKRED = 0x04 # dark red. +FOREGROUND_DARKPINK = 0x05 # dark pink. +FOREGROUND_DARKYELLOW = 0x06 # dark yellow. +FOREGROUND_DARKWHITE = 0x07 # dark white. +FOREGROUND_DARKGRAY = 0x08 # dark gray. +FOREGROUND_BLUE = 0x09 # blue. +FOREGROUND_GREEN = 0x0a # green. +FOREGROUND_SKYBLUE = 0x0b # skyblue. +FOREGROUND_RED = 0x0c # red. +FOREGROUND_PINK = 0x0d # pink. +FOREGROUND_YELLOW = 0x0e # yellow. +FOREGROUND_WHITE = 0x0f # white. + # Windows CMD命令行 背景颜色定义 background colors -BACKGROUND_BLUE = 0x10 # dark blue. -BACKGROUND_GREEN = 0x20 # dark green. -BACKGROUND_DARKSKYBLUE = 0x30 # dark skyblue. -BACKGROUND_DARKRED = 0x40 # dark red. -BACKGROUND_DARKPINK = 0x50 # dark pink. -BACKGROUND_DARKYELLOW = 0x60 # dark yellow. -BACKGROUND_DARKWHITE = 0x70 # dark white. -BACKGROUND_DARKGRAY = 0x80 # dark gray. -BACKGROUND_BLUE = 0x90 # blue. -BACKGROUND_GREEN = 0xa0 # green. -BACKGROUND_SKYBLUE = 0xb0 # skyblue. -BACKGROUND_RED = 0xc0 # red. -BACKGROUND_PINK = 0xd0 # pink. -BACKGROUND_YELLOW = 0xe0 # yellow. -BACKGROUND_WHITE = 0xf0 # white. - - - +BACKGROUND_BLUE = 0x10 # dark blue. +BACKGROUND_GREEN = 0x20 # dark green. +BACKGROUND_DARKSKYBLUE = 0x30 # dark skyblue. +BACKGROUND_DARKRED = 0x40 # dark red. +BACKGROUND_DARKPINK = 0x50 # dark pink. +BACKGROUND_DARKYELLOW = 0x60 # dark yellow. +BACKGROUND_DARKWHITE = 0x70 # dark white. +BACKGROUND_DARKGRAY = 0x80 # dark gray. +BACKGROUND_BLUE = 0x90 # blue. +BACKGROUND_GREEN = 0xa0 # green. +BACKGROUND_SKYBLUE = 0xb0 # skyblue. +BACKGROUND_RED = 0xc0 # red. +BACKGROUND_PINK = 0xd0 # pink. +BACKGROUND_YELLOW = 0xe0 # yellow. +BACKGROUND_WHITE = 0xf0 # white. + # get handle std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) - + + def set_cmd_text_color(color, handle=std_out_handle): Bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color) return Bool - -#reset white + + +# reset white def resetColor(): set_cmd_text_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE) - + + ############################################################### - -#暗蓝色 -#dark blue + +# 暗蓝色 +# dark blue def printDarkBlue(mess): set_cmd_text_color(FOREGROUND_DARKBLUE) sys.stdout.write(mess) resetColor() - -#暗绿色 -#dark green + + +# 暗绿色 +# dark green def printDarkGreen(mess): set_cmd_text_color(FOREGROUND_DARKGREEN) sys.stdout.write(mess) resetColor() - -#暗天蓝色 -#dark sky blue + + +# 暗天蓝色 +# dark sky blue def printDarkSkyBlue(mess): set_cmd_text_color(FOREGROUND_DARKSKYBLUE) sys.stdout.write(mess) resetColor() - -#暗红色 -#dark red + + +# 暗红色 +# dark red def printDarkRed(mess): set_cmd_text_color(FOREGROUND_DARKRED) sys.stdout.write(mess) resetColor() - -#暗粉红色 -#dark pink + + +# 暗粉红色 +# dark pink def printDarkPink(mess): set_cmd_text_color(FOREGROUND_DARKPINK) sys.stdout.write(mess) resetColor() - -#暗黄色 -#dark yellow + + +# 暗黄色 +# dark yellow def printDarkYellow(mess): set_cmd_text_color(FOREGROUND_DARKYELLOW) sys.stdout.write(mess) resetColor() - -#暗白色 -#dark white + + +# 暗白色 +# dark white def printDarkWhite(mess): set_cmd_text_color(FOREGROUND_DARKWHITE) sys.stdout.write(mess) resetColor() - -#暗灰色 -#dark gray + + +# 暗灰色 +# dark gray def printDarkGray(mess): set_cmd_text_color(FOREGROUND_DARKGRAY) sys.stdout.write(mess) resetColor() - -#蓝色 -#blue + + +# 蓝色 +# blue def printBlue(mess): set_cmd_text_color(FOREGROUND_BLUE) sys.stdout.write(mess) resetColor() - -#绿色 -#green + + +# 绿色 +# green def printGreen(mess): set_cmd_text_color(FOREGROUND_GREEN) sys.stdout.write(mess) resetColor() - -#天蓝色 -#sky blue + + +# 天蓝色 +# sky blue def printSkyBlue(mess): set_cmd_text_color(FOREGROUND_SKYBLUE) sys.stdout.write(mess) resetColor() - -#红色 -#red + + +# 红色 +# red def printRed(mess): set_cmd_text_color(FOREGROUND_RED) sys.stdout.write(mess) resetColor() - -#粉红色 -#pink + + +# 粉红色 +# pink def printPink(mess): set_cmd_text_color(FOREGROUND_PINK) sys.stdout.write(mess) resetColor() - -#黄色 -#yellow + + +# 黄色 +# yellow def printYellow(mess): set_cmd_text_color(FOREGROUND_YELLOW) sys.stdout.write(mess) resetColor() - -#白色 -#white + + +# 白色 +# white def printWhite(mess): set_cmd_text_color(FOREGROUND_WHITE) sys.stdout.write(mess) resetColor() - + + ################################################## - -#白底黑字 -#white bkground and black text + +# 白底黑字 +# white bkground and black text def printWhiteBlack(mess): set_cmd_text_color(FOREGROUND_BLACK | BACKGROUND_WHITE) sys.stdout.write(mess) resetColor() - -#白底黑字 -#white bkground and black text + + +# 白底黑字 +# white bkground and black text def printWhiteBlack_2(mess): set_cmd_text_color(0xf0) sys.stdout.write(mess) resetColor() - - -#黄底蓝字 -#white bkground and black text + + +# 黄底蓝字 +# white bkground and black text def printYellowRed(mess): set_cmd_text_color(BACKGROUND_YELLOW | FOREGROUND_RED) sys.stdout.write(mess) resetColor() - - + + ############################################################## - + if __name__ == '__main__': - printDarkBlue('printDarkBlue:暗蓝色文字\n') - printDarkGreen('printDarkGreen:暗绿色文字\n' ) - printDarkSkyBlue('printDarkSkyBlue:暗天蓝色文字\n' ) - printDarkRed('printDarkRed:暗红色文字\n' ) - printDarkPink('printDarkPink:暗粉红色文字\n' ) - printDarkYellow('printDarkYellow:暗黄色文字\n' ) - printDarkWhite('printDarkWhite:暗白色文字\n' ) - printDarkGray('printDarkGray:暗灰色文字\n' ) - printBlue('printBlue:蓝色文字\n' ) - printGreen('printGreen:绿色文字\n' ) - printSkyBlue('printSkyBlue:天蓝色文字\n' ) - printRed('printRed:红色文字\n' ) - printPink('printPink:粉红色文字\n' ) - printYellow('printYellow:黄色文字\n' ) - printWhite('printWhite:白色文字\n' ) - - printWhiteBlack('printWhiteBlack:白底黑字输出\n' ) - printWhiteBlack_2('printWhiteBlack_2:白底黑字输出(直接传入16进制参数)\n' ) - printYellowRed('printYellowRed:黄底红字输出\n' ) \ No newline at end of file + printDarkGreen('printDarkGreen:暗绿色文字\n') + printDarkSkyBlue('printDarkSkyBlue:暗天蓝色文字\n') + printDarkRed('printDarkRed:暗红色文字\n') + printDarkPink('printDarkPink:暗粉红色文字\n') + printDarkYellow('printDarkYellow:暗黄色文字\n') + printDarkWhite('printDarkWhite:暗白色文字\n') + printDarkGray('printDarkGray:暗灰色文字\n') + printBlue('printBlue:蓝色文字\n') + printGreen('printGreen:绿色文字\n') + printSkyBlue('printSkyBlue:天蓝色文字\n') + printRed('printRed:红色文字\n') + printPink('printPink:粉红色文字\n') + printYellow('printYellow:黄色文字\n') + printWhite('printWhite:白色文字\n') + + printWhiteBlack('printWhiteBlack:白底黑字输出\n') + printWhiteBlack_2('printWhiteBlack_2:白底黑字输出(直接传入16进制参数)\n') + printYellowRed('printYellowRed:黄底红字输出\n') diff --git a/src/decoder.py b/src/decoder.py index a5a67ab..2aea1ee 100644 --- a/src/decoder.py +++ b/src/decoder.py @@ -1,13 +1,13 @@ #! python # -*- coding:utf-8 -*- +import json +import openpyxl import os import re import sys -import json -import openpyxl -import color_print +import color_print from slpp.slpp import slpp as lua # array鏁扮粍妯″紡涓嬶紝鍚勪釜鏍忕殑鍒嗗竷 绗竴琛岃鏄枃妗f敞閲婏紝涓嶅鍑 @@ -25,8 +25,8 @@ OCLT_COL = 4 # client column 瀹㈡埛绔 OCTX_COL = 5 # content column 鍐呭鎵鍦ㄥ垪 OFLG_ROW = 2 # flag object妯″紡涓 server client鎵鍦ㄨ -SHEET_FLAG_ROW = 2 # 2鍒1琛岃〃绀烘槸array 杩樻槸object 鎴栬呮槸涓嶇敤瀵煎嚭鐨勮〃 -SHEET_FLAG_COL = 1 # 2鍒1琛岃〃绀烘槸array 杩樻槸object 鎴栬呮槸涓嶇敤瀵煎嚭鐨勮〃 +SHEET_FLAG_ROW = 2 # 2鍒1琛岃〃绀烘槸array 杩樻槸object 鎴栬呮槸涓嶇敤瀵煎嚭鐨勮〃 +SHEET_FLAG_COL = 1 # 2鍒1琛岃〃绀烘槸array 杩樻槸object 鎴栬呮槸涓嶇敤瀵煎嚭鐨勮〃 # 瀵煎嚭鏈嶅姟鍣/瀹㈡埛绔厤缃爣璇 SRV_FLAG = "server" @@ -38,19 +38,18 @@ ALIST_COL = 1 SRV_LIST = "slist" CLT_LIST = "clist" - # 鐢ㄤ簬鏍囪瘑琛ㄧ殑绫诲瀷 涓嶆槸杩欎袱绉嶅氨涓嶄細瀵煎嚭鏁版嵁 -ARRAY_FLAG = "array" # 鏍囪瘑琛ㄧ殑鏄痑rray绫诲瀷鐨勮〃 +ARRAY_FLAG = "array" # 鏍囪瘑琛ㄧ殑鏄痑rray绫诲瀷鐨勮〃 OBJECT_FLAG = "object" # 鏍囪瘑琛ㄧ殑鏄痮bject绫诲瀷鐨勮〃 -KEY_FLAG = "$key_" # array琛ㄧ殑 浣滀负Key瀛楁鐨勫墠缂鏍囪瘑 -KEY_FLAG_LEN = 5 # array琛ㄧ殑 浣滀负Key瀛楁鐨勫墠缂鏍囪瘑闀垮害 鐢ㄤ簬鍒嗗壊瀛楃涓 +KEY_FLAG = "$key_" # array琛ㄧ殑 浣滀负Key瀛楁鐨勫墠缂鏍囪瘑 +KEY_FLAG_LEN = 5 # array琛ㄧ殑 浣滀负Key瀛楁鐨勫墠缂鏍囪瘑闀垮害 鐢ㄤ簬鍒嗗壊瀛楃涓 # 鏀寔鐨勬暟鎹被鍨 # "int":1,"number":2,"int64":3,"string":4, "tuple":5, "list":6, "dict":7 涓簆ython鍘熺敓鏁版嵁鏍煎紡 # "json":8,"lua":9 涓簀son鍜宭ua鐨勬暟鎹牸寮 # excel閰嶇疆鐨勬椂鍊 瀵瑰簲绫诲瀷瀛楁 濉叆瀵瑰簲鏁版嵁绫诲瀷鐨勬湁鏁堟暟鎹牸寮忕殑鏁版嵁灏監K -TYPES = { "int":1,"number":2,"int64":3,"string":4, "tuple":5, "list":6, "dict":7, "json":8,"lua":9} +TYPES = {"int": 1, "number": 2, "int64": 3, "string": 4, "tuple": 5, "list": 6, "dict": 7, "json": 8, "lua": 9} try: basestring @@ -69,6 +68,7 @@ try: except NameError: unicode = str + # 绫诲瀷杞崲鍣 class ValueConverter(object): def __init__(self): @@ -78,67 +78,68 @@ class ValueConverter(object): # str鍙互閫氳繃decode杞崲涓簎nicode # ascii' codec can't encode characters # 杩欎釜鍑芥暟鍦╬ython3涓病鐢 - def to_unicode_str( self,val ): - if isinstance( val,str ) : + def to_unicode_str(self, val): + if isinstance(val, str): return val - elif isinstance( val,unicode ) : + elif isinstance(val, unicode): return val - else : - return str( val ).decode("utf8") - - def to_value(self,val_type,val): - if "int" == val_type : - return int( val ) - elif "int64" == val_type : - return long( val ) - elif "number" == val_type : + else: + return str(val).decode("utf8") + + def to_value(self, val_type, val): + if "int" == val_type: + return int(val) + elif "int64" == val_type: + return long(val) + elif "number" == val_type: # 鍘婚櫎甯﹀皬鏁版椂鐨勫皬鏁扮偣锛100.0 ==>> 100 # number灏辫瀹冨甫灏忔暟鐐瑰惂锛屼笉鐒跺己绫诲瀷鐨勯厤缃棤娉曟纭瘑鍒嚭鏉 # if long( val ) == float( val ) : return long( val ) - return float( val ) - elif "string" == val_type : - return self.to_unicode_str( val ) - elif "json" == val_type : - return json.loads( val ) - elif "lua" == val_type : - return lua.decode( val ) - elif "tuple" == val_type : - return tuple(eval(val)) - elif "list" == val_type : + return float(val) + elif "string" == val_type: + return self.to_unicode_str(val) + elif "json" == val_type: + return json.loads(val) + elif "lua" == val_type: + return lua.decode(val) + elif "tuple" == val_type: + return tuple(eval(val)) + elif "list" == val_type: return list(eval(val)) - elif "dict" == val_type : + elif "dict" == val_type: return dict(eval(val)) - else : - self.raise_error( "invalid type",value ) + else: + self.raise_error("invalid type", value) + class Sheet(object): def __init__(self, base_name, wb_sheet, srv_writer, clt_writer, srv_is_list, clt_is_list): - self.types = [] # 璁板綍鍚勫垪瀛楁鐨勭被鍨 + self.types = [] # 璁板綍鍚勫垪瀛楁鐨勭被鍨 self.srv_writer = srv_writer self.clt_writer = clt_writer - self.srv_fields = [] #鏈嶅姟绔悇鍒楀瓧娈靛悕 - self.clt_fields = [] #瀹㈡埛绔悇鍒楀瓧娈靛悕 - self.srv_comment = {} # 鏈嶅姟鍣ㄥ瓧娈垫敞閲 - self.clt_comment = {} # 瀹㈡埛绔瓧娈垫敞閲 + self.srv_fields = [] # 鏈嶅姟绔悇鍒楀瓧娈靛悕 + self.clt_fields = [] # 瀹㈡埛绔悇鍒楀瓧娈靛悕 + self.srv_comment = {} # 鏈嶅姟鍣ㄥ瓧娈垫敞閲 + self.clt_comment = {} # 瀹㈡埛绔瓧娈垫敞閲 - self.srv_keys = {} # 鏈嶅姟鍣╧ey - self.clt_keys = {} # 瀹㈡埛绔痥ey + self.srv_keys = {} # 鏈嶅姟鍣╧ey + self.clt_keys = {} # 瀹㈡埛绔痥ey self.srv_is_list = srv_is_list # 瀹㈡埛绔槸鍚﹀鑷磄et_list() 鍒楄〃鍑芥暟 self.clt_is_list = clt_is_list # 瀹㈡埛绔槸鍚﹀鑷磄et_list() 鍒楄〃鍑芥暟 self.converter = ValueConverter() - self.wb_sheet = wb_sheet + self.wb_sheet = wb_sheet self.base_name = base_name - match_list = re.findall("[a-zA-Z0-9_]+$",base_name) + match_list = re.findall("[a-zA-Z0-9_]+$", base_name) if None == match_list or 1 != len(match_list): - Exception( base_name,"not a legal file name" ) + Exception(base_name, "not a legal file name") self.base_file_name = match_list[0] @@ -147,42 +148,42 @@ class Sheet(object): self.error_col = 0 # 璁板綍鍑洪敊浣嶇疆 - def mark_error_pos(self,row,col): - if row > 0 : self.error_row = row - if col > 0 : self.error_col = col + def mark_error_pos(self, row, col): + if row > 0: self.error_row = row + if col > 0: self.error_col = col # 鍙戣捣涓涓В鏋愰敊璇 - def raise_error(self,what,val): + def raise_error(self, what, val): excel_info = format("DOC:%s,SHEET:%s,ROW:%d,COLUMN:%d" % \ - (self.base_name,self.wb_sheet.title,self.error_row,self.error_col)) - raise Exception( what,val,excel_info ) + (self.base_name, self.wb_sheet.title, self.error_row, self.error_col)) + raise Exception(what, val, excel_info) - def to_value(self,val_type,val): + def to_value(self, val_type, val): try: - return self.converter.to_value(val_type,val) - except Exception : + return self.converter.to_value(val_type, val) + except Exception: t, e = sys.exc_info()[:2] - self.raise_error( "ConverError",e ) + self.raise_error("ConverError", e) # 瑙f瀽涓涓〃鏍 def decode_sheet(self): wb_sheet = self.wb_sheet - self.decode_type () + self.decode_type() self.decode_field() - self.decode_ctx () + self.decode_ctx() - color_print.printGreen( " covert successfully... sheet name -> %s \n" % wb_sheet.title ) + color_print.printGreen(" covert successfully... sheet name -> %s \n" % wb_sheet.title) return True # 鍐欏叆閰嶇疆鍒版枃浠 def write_one_file(self, ctx, base_path, writer, keys_list, comment_text, is_list): # 鏈変簺閰嶇疆鍙兘鍙鍑哄鎴风鎴栧彧瀵煎嚭鏈嶅姟鍣 - if not any(ctx) : + if not any(ctx): return write_file_name = self.base_file_name - if self.wb_sheet.title.find("+") >= 0 or self.wb_sheet.title.find("-") >= 0 : + if self.wb_sheet.title.find("+") >= 0 or self.wb_sheet.title.find("-") >= 0: match_list = re.findall("[a-zA-Z0-9_]+$", self.wb_sheet.title) if 1 == len(match_list): write_file_name = write_file_name + '_' + match_list[0] @@ -190,20 +191,23 @@ class Sheet(object): wt = writer(self.base_name, self.wb_sheet.title, write_file_name, keys_list, comment_text, is_list) ctx = wt.context(ctx) suffix = wt.suffix() - if None != ctx : + if None != ctx: path = base_path + write_file_name + suffix - #蹇呴』涓簑b锛屼笉鐒舵棤娉曞啓鍏tf-8 - file = open( path, 'wb' ) - file.write( ctx.encode( "utf-8" ) ) + # 蹇呴』涓簑b锛屼笉鐒舵棤娉曞啓鍏tf-8 + file = open(path, 'wb') + file.write(ctx.encode("utf-8")) file.close() # 鍒嗗埆鍐欏叆鍒版湇鍔$銆佸鎴风鐨勯厤缃枃浠 def write_files(self, srv_path, clt_path): if None != srv_path and None != self.srv_writer: - self.write_one_file(self.srv_ctx, srv_path, self.srv_writer, self.srv_keys, self.srv_comment, self.srv_is_list) + self.write_one_file(self.srv_ctx, srv_path, self.srv_writer, self.srv_keys, self.srv_comment, + self.srv_is_list) if None != clt_path and None != self.clt_writer: - self.write_one_file(self.clt_ctx, clt_path, self.clt_writer, self.clt_keys, self.clt_comment, self.clt_is_list) + self.write_one_file(self.clt_ctx, clt_path, self.clt_writer, self.clt_keys, self.clt_comment, + self.clt_is_list) + # 瀵煎嚭鏁扮粍绫诲瀷閰嶇疆锛孉1鏍煎瓙鐨勫唴瀹规湁array鏍囪瘑 class ArraySheet(Sheet): @@ -219,103 +223,103 @@ class ArraySheet(Sheet): # 瑙f瀽鍚勫垪鐨勭被鍨(string銆乶umber...) def decode_type(self): # 绗竴鍒楁病鏁版嵁锛岀被鍨嬪彲浠ヤ笉濉紝榛樿涓篘one锛屼絾鏄繖閲岃鍗犱釜浣 - self.types.append( None ) + self.types.append(None) - for col_idx in range( AKEY_COL + 1,self.wb_sheet.max_column + 1 ): - self.mark_error_pos(ATPE_ROW,col_idx) - value = self.wb_sheet.cell( row = ATPE_ROW, column = col_idx ).value + for col_idx in range(AKEY_COL + 1, self.wb_sheet.max_column + 1): + self.mark_error_pos(ATPE_ROW, col_idx) + value = self.wb_sheet.cell(row=ATPE_ROW, column=col_idx).value # 鍗曞厓鏍间负绌虹殑鏃跺欙紝wb_sheet.cell(row=1, column=2).value == None # 绫诲瀷閭d竴琛屽繀椤昏繛缁紝绌虹櫧琛ㄧず鍚庨潰鐨勬暟鎹兘涓嶅鍑轰簡 - if value == None : + if value == None: break - if value not in TYPES : - self.raise_error( "invalid type",value ) + if value not in TYPES: + self.raise_error("invalid type", value) - self.types.append( value ) + self.types.append(value) # 瑙f瀽瀹㈡埛绔佹湇鍔″櫒鐨勫瓧娈靛悕(server銆乧lient)閭d袱琛 - def decode_one_field(self,fields,row_index, keys): + def decode_one_field(self, fields, row_index, keys): key_index = 1 - for col_index in range( AKEY_COL,len( self.types ) + 1 ): + for col_index in range(AKEY_COL, len(self.types) + 1): value = self.wb_sheet.cell( - row = row_index, column = col_index ).value + row=row_index, column=col_index).value # 瀵逛簬array绫诲瀷鐨勮〃 涓鏉℃暟鎹彲浠ユ湁澶氫釜鍊间綔涓篕EY 闇瑕佸鐞嗕竴涓 - if None != value and value.find(KEY_FLAG) >= 0 : + if None != value and value.find(KEY_FLAG) >= 0: value = value[KEY_FLAG_LEN:] keys[value] = key_index key_index = key_index + 1 # 瀵逛簬涓嶉渶瑕佸鍑虹殑field锛屽彲浠ヤ负绌恒傚嵆value涓篘one - fields.append( value ) + fields.append(value) # 瑙f瀽娉ㄩ噴閭d竴琛 - def decode_one_comment(self,fields,row_index, key_index): - for col_index in range( AKEY_COL + 1,len( self.types ) + 1 ): + def decode_one_comment(self, fields, row_index, key_index): + for col_index in range(AKEY_COL + 1, len(self.types) + 1): value = self.wb_sheet.cell( - row = row_index, column = col_index ).value + row=row_index, column=col_index).value key = self.wb_sheet.cell( - row = key_index, column = col_index ).value + row=key_index, column=col_index).value - if None == key : + if None == key: continue # 瀵逛簬涓嶉渶瑕佸鍑虹殑field锛屽彲浠ヤ负绌恒傚嵆value涓篘one - if key.find(KEY_FLAG) >= 0 : + if key.find(KEY_FLAG) >= 0: key = key[KEY_FLAG_LEN:] fields[key] = value - else : + else: fields[key] = value # 瀵煎嚭瀹㈡埛绔佹湇鍔$瀛楁鍚(server銆乧lient)閭d竴鍒 def decode_field(self): - self.decode_one_field( self.srv_fields,ASRV_ROW, self.srv_keys ) - self.decode_one_field( self.clt_fields,ACLT_ROW, self.clt_keys ) + self.decode_one_field(self.srv_fields, ASRV_ROW, self.srv_keys) + self.decode_one_field(self.clt_fields, ACLT_ROW, self.clt_keys) # 瀵煎嚭鏈嶅姟鍣ㄥ拰瀹㈡埛绔鐢ㄥ瓧娈电殑娉ㄩ噴锛 瀵艰〃鐨勬椂鍊欏彲鑳界敤鍒 - self.decode_one_comment( self.srv_comment, ACMT_ROW, ASRV_ROW) - self.decode_one_comment( self.clt_comment, ACMT_ROW, ACLT_ROW) + self.decode_one_comment(self.srv_comment, ACMT_ROW, ASRV_ROW) + self.decode_one_comment(self.clt_comment, ACMT_ROW, ACLT_ROW) # 瑙f瀽鍑轰竴涓牸瀛愮殑鍐呭 - def decode_cell(self,row_idx,col_idx): - value = self.wb_sheet.cell( row = row_idx, column = col_idx ).value + def decode_cell(self, row_idx, col_idx): + value = self.wb_sheet.cell(row=row_idx, column=col_idx).value if None == value: return None # 绫诲瀷鏄粠0涓嬫爣寮濮嬶紝浣嗘槸excel鐨勭涓鍒椾粠1寮濮 - self.mark_error_pos( row_idx,col_idx ) - return self.to_value( self.types[col_idx - 1],value ) + self.mark_error_pos(row_idx, col_idx) + return self.to_value(self.types[col_idx - 1], value) # 瑙f瀽鍑轰竴琛岀殑鍐呭 - def decode_row(self,row_idx): + def decode_row(self, row_idx): srv_row = {} clt_row = {} # 绗竴鍒楁病鏁版嵁锛屼粠绗簩鍒楀紑濮嬭В鏋 - for col_idx in range( AKEY_COL + 1,len( self.types ) + 1 ): - value = self.decode_cell( row_idx,col_idx ) - if None == value : continue + for col_idx in range(AKEY_COL + 1, len(self.types) + 1): + value = self.decode_cell(row_idx, col_idx) + if None == value: continue srv_key = self.srv_fields[col_idx - 1] clt_key = self.clt_fields[col_idx - 1] - - if srv_key : + if srv_key: srv_row[srv_key] = value - if clt_key : + if clt_key: clt_row[clt_key] = value - return srv_row,clt_row # 杩斿洖涓涓猼uple + return srv_row, clt_row # 杩斿洖涓涓猼uple # 瑙f瀽瀵煎嚭鐨勫唴瀹 def decode_ctx(self): - for row_idx in range( ACLT_ROW + 1,self.wb_sheet.max_row + 1 ): - srv_row,clt_row = self.decode_row( row_idx ) + for row_idx in range(ACLT_ROW + 1, self.wb_sheet.max_row + 1): + srv_row, clt_row = self.decode_row(row_idx) # 涓嶄负绌烘墠杩藉姞 - if any( srv_row ) : - self.srv_ctx.append( srv_row ) - if any( clt_row ) : - self.clt_ctx.append( clt_row ) + if any(srv_row): + self.srv_ctx.append(srv_row) + if any(clt_row): + self.clt_ctx.append(clt_row) + # 瀵煎嚭object绫诲瀷鐨勭粨鏋勶紝A1鏍煎瓙鏈塷bject鏍囪瘑 class ObjectSheet(Sheet): @@ -330,80 +334,81 @@ class ObjectSheet(Sheet): # 瑙f瀽鍚勫瓧娈电殑绫诲瀷 def decode_type(self): - for row_idx in range( OFLG_ROW + 1,self.wb_sheet.max_row + 1 ): - self.mark_error_pos( row_idx,OTPE_COL) - value = self.wb_sheet.cell( row = row_idx, column = OTPE_COL ).value + for row_idx in range(OFLG_ROW + 1, self.wb_sheet.max_row + 1): + self.mark_error_pos(row_idx, OTPE_COL) + value = self.wb_sheet.cell(row=row_idx, column=OTPE_COL).value # 绫诲瀷蹇呴』杩炵画锛岄亣鍒扮┖鍒欒涓哄悗缁暟鎹笉鍐嶅鍑 - if value == None : + if value == None: break - if value not in TYPES : - self.raise_error( "invalid type",value ) + if value not in TYPES: + self.raise_error("invalid type", value) - self.types.append( value ) + self.types.append(value) # 瀵煎嚭瀹㈡埛绔佹湇鍔$瀛楁鍚(server銆乧lient)閭d竴鍒 - def decode_one_field(self,fields,col_idx): - for row_idx in range( OFLG_ROW + 1,len( self.types ) + OFLG_ROW + 1 ): - value = self.wb_sheet.cell( row = row_idx, column = col_idx ).value + def decode_one_field(self, fields, col_idx): + for row_idx in range(OFLG_ROW + 1, len(self.types) + OFLG_ROW + 1): + value = self.wb_sheet.cell(row=row_idx, column=col_idx).value # 瀵逛簬涓嶉渶瑕佸鍑虹殑field锛屽彲浠ヤ负绌恒傚嵆value涓篘one - fields.append( value ) + fields.append(value) # 瑙f瀽娉ㄩ噴閭d竴琛 - def decode_one_comment(self,fields,col_idx, key_index): - for row_idx in range( OFLG_ROW + 1,len( self.types ) + OFLG_ROW + 1 ): - value = self.wb_sheet.cell( row = row_idx, column = col_idx ).value + def decode_one_comment(self, fields, col_idx, key_index): + for row_idx in range(OFLG_ROW + 1, len(self.types) + OFLG_ROW + 1): + value = self.wb_sheet.cell(row=row_idx, column=col_idx).value - key = self.wb_sheet.cell( row = row_idx, column = key_index ).value + key = self.wb_sheet.cell(row=row_idx, column=key_index).value if None == value: continue # 瀵煎嚭瀛樺湪鍊肩殑fields鐨勬敞閲 - fields[key] = value + fields[key] = value # 瀵煎嚭瀹㈡埛绔佹湇鍔$瀛楁鍚(server銆乧lient)閭d竴鍒 def decode_field(self): - self.decode_one_field( self.srv_fields,OSRV_COL ) - self.decode_one_field( self.clt_fields,OCLT_COL ) + self.decode_one_field(self.srv_fields, OSRV_COL) + self.decode_one_field(self.clt_fields, OCLT_COL) # 瀵煎嚭鏈嶅姟鍣ㄥ拰瀹㈡埛绔鐢ㄥ瓧娈电殑娉ㄩ噴锛 瀵艰〃鐨勬椂鍊欏彲鑳界敤鍒 - self.decode_one_comment( self.srv_comment, OCMT_COL, OSRV_COL) - self.decode_one_comment( self.clt_comment, OCMT_COL, OCLT_COL ) + self.decode_one_comment(self.srv_comment, OCMT_COL, OSRV_COL) + self.decode_one_comment(self.clt_comment, OCMT_COL, OCLT_COL) # 瑙f瀽涓涓崟鍏冩牸鍐呭 - def decode_cell(self,row_idx): - value = self.wb_sheet.cell( row = row_idx, column = OCTX_COL ).value - if None == value : return None + def decode_cell(self, row_idx): + value = self.wb_sheet.cell(row=row_idx, column=OCTX_COL).value + if None == value: return None # 鍦╫bject鐨勭粨鏋勪腑锛屾暟鎹槸浠庣浜岃寮濮嬬殑锛屾墍浠ypes鐨勪笅鏍囧亸绉2 - self.mark_error_pos( row_idx,OCTX_COL ) - return self.to_value( self.types[row_idx - OFLG_ROW - 1],value ) + self.mark_error_pos(row_idx, OCTX_COL) + return self.to_value(self.types[row_idx - OFLG_ROW - 1], value) # 瑙f瀽琛ㄦ牸鐨勬墍鏈夊唴瀹 def decode_ctx(self): - for row_idx in range( OFLG_ROW + 1,len( self.types ) + OFLG_ROW + 1 ): - value = self.decode_cell( row_idx ) + for row_idx in range(OFLG_ROW + 1, len(self.types) + OFLG_ROW + 1): + value = self.decode_cell(row_idx) - if None == value : + if None == value: continue srv_key = self.srv_fields[row_idx - OFLG_ROW - 1] clt_key = self.clt_fields[row_idx - OFLG_ROW - 1] - if srv_key : self.srv_ctx[srv_key] = value - if clt_key : self.clt_ctx[clt_key] = value + if srv_key: self.srv_ctx[srv_key] = value + if clt_key: self.clt_ctx[clt_key] = value + class ExcelDoc: - def __init__(self, file,abspath): + def __init__(self, file, abspath): self.file = file self.abspath = abspath # 鏄惁闇瑕佽В鏋 # 杩斿洖瑙f瀽鐨勫璞$被鍨 - def need_decode(self,wb_sheet): + def need_decode(self, wb_sheet): sheet_val = wb_sheet.cell( - row = SHEET_FLAG_ROW, column = SHEET_FLAG_COL ).value + row=SHEET_FLAG_ROW, column=SHEET_FLAG_COL).value sheeter = None srv_value = None @@ -437,17 +442,17 @@ class ExcelDoc: return None, srv_is_list, clt_is_list return sheeter, srv_is_list, clt_is_list - def decode(self,srv_path,clt_path,srv_writer,clt_writer): + def decode(self, srv_path, clt_path, srv_writer, clt_writer): color_print.printYellow(" start covert: %s \n" % self.file.ljust(44, "*")) - base_name = os.path.splitext( self.file )[0] - wb = openpyxl.load_workbook( self.abspath ) + base_name = os.path.splitext(self.file)[0] + wb = openpyxl.load_workbook(self.abspath) for wb_sheet in wb.worksheets: - Sheeter, srv_is_list, clt_is_list = self.need_decode( wb_sheet ) - if None == Sheeter : + Sheeter, srv_is_list, clt_is_list = self.need_decode(wb_sheet) + if None == Sheeter: color_print.printPink(" covert skip........... sheet name -> %s\n" % wb_sheet.title) continue - sheet = Sheeter( base_name,wb_sheet,srv_writer,clt_writer, srv_is_list, clt_is_list ) - if sheet.decode_sheet() : - sheet.write_files( srv_path,clt_path ) \ No newline at end of file + sheet = Sheeter(base_name, wb_sheet, srv_writer, clt_writer, srv_is_list, clt_is_list) + if sheet.decode_sheet(): + sheet.write_files(srv_path, clt_path) diff --git a/src/genCfgs.py b/src/genCfgs.py index 60ac6ae..3c35ca1 100644 --- a/src/genCfgs.py +++ b/src/genCfgs.py @@ -16,97 +16,98 @@ from optparse import OptionParser from decoder import ExcelDoc + class Reader: # @input_path:excel鏂囦欢鎵鍦ㄧ洰褰 # @srv_path :server杈撳嚭鐩綍 # @clt_path :瀹㈡埛绔緭鍑虹洰褰 # @timeout :鍙鐞嗘枃妗f渶鍚庢洿鏀规椂闂村湪N绉掑唴鐨勬枃妗 # @suffix :excel鏂囦欢鍚庣紑 - def __init__(self,input_path, - srv_path,clt_path,timeout,suffix,srv_writer,clt_writer): + def __init__(self, input_path, + srv_path, clt_path, timeout, suffix, srv_writer, clt_writer): self.input_path = input_path - self.srv_path = srv_path - self.clt_path = clt_path - self.timeout = timeout - self.suffix = suffix + self.srv_path = srv_path + self.clt_path = clt_path + self.timeout = timeout + self.suffix = suffix self.srv_writer = None self.clt_writer = None - if None != srv_writer : - self.srv_writer = eval( srv_writer.capitalize() + "Writer" ) - if None != clt_writer : - self.clt_writer = eval( clt_writer.capitalize() + "Writer" ) + if None != srv_writer: + self.srv_writer = eval(srv_writer.capitalize() + "Writer") + if None != clt_writer: + self.clt_writer = eval(clt_writer.capitalize() + "Writer") def attention(self): print("*****************************寮濮嬪琛*****************************\n") - def can_read(self,file,abspath): - if not os.path.isfile( abspath ): return False + def can_read(self, file, abspath): + if not os.path.isfile(abspath): return False # ~寮澶寸殑excel鏂囦欢鏄复鏃舵枃浠讹紝linux涓媤ps涓存椂鏂囦欢浠.~寮澶 - if file.startswith( "~" ) \ - or file.startswith( "." ) or file.startswith( "$" ): return False - if "" != self.suffix and not file.endswith( self.suffix ): return False + if file.startswith("~") \ + or file.startswith(".") or file.startswith("$"): return False + if "" != self.suffix and not file.endswith(self.suffix): return False if self.timeout > 0: now = time.time() - mtime = os.path.getmtime( abspath ) + mtime = os.path.getmtime(abspath) if now - mtime > self.timeout: return False return True def read(self): - if self.timeout > 0 : + if self.timeout > 0: print("read %s files from %s modified \ - within %d seconds" % (self.suffix,self.input_path,self.timeout)) - else : - print("read %s files from %s" % (self.suffix,self.input_path)) + within %d seconds" % (self.suffix, self.input_path, self.timeout)) + else: + print("read %s files from %s" % (self.suffix, self.input_path)) - if None != self.srv_path and not os.path.exists( self.srv_path ) : - os.makedirs( self.srv_path ) - if None != self.clt_path and not os.path.exists( self.clt_path ) : - os.makedirs( self.clt_path ) + if None != self.srv_path and not os.path.exists(self.srv_path): + os.makedirs(self.srv_path) + if None != self.clt_path and not os.path.exists(self.clt_path): + os.makedirs(self.clt_path) now = time.time() - file_list = os.listdir( options.input_path ) + file_list = os.listdir(options.input_path) for file in file_list: - abspath = os.path.join( self.input_path,file ) - if self.can_read( file,abspath ) : - self.read_one( file,abspath ) + abspath = os.path.join(self.input_path, file) + if self.can_read(file, abspath): + self.read_one(file, abspath) - print( "done,%d seconds elapsed" % ( time.time() - now ) ) + print("done,%d seconds elapsed" % (time.time() - now)) - def read_one(self,file,abspath): - doc = ExcelDoc( file,abspath ) - doc.decode( self.srv_path, - self.clt_path,self.srv_writer,self.clt_writer ) + def read_one(self, file, abspath): + doc = ExcelDoc(file, abspath) + doc.decode(self.srv_path, + self.clt_path, self.srv_writer, self.clt_writer) -if __name__ == '__main__': +if __name__ == '__main__': parser = OptionParser() - parser.add_option( "-i", "--input", dest="input_path", - default="xls/", - help="read all files from this path" ) - parser.add_option( "-s", "--srv", dest="srv_path", - help="write all server file to this path" ) - parser.add_option( "-c", "--clt", dest="clt_path", - help="write all client file to this path" ) - parser.add_option( "-t", "--timeout", dest="timeout",type="int", - default="-1", - help="only converte files modified within seconds" ) - parser.add_option( "-f", "--suffix", dest="suffix", - default="", - help="what type of file will be readed.empty mean all files" ) - parser.add_option( "-w","--swriter", dest="srv_writer", - help="which server writer you wish to use:lua xml json" ) - parser.add_option( "-l","--cwriter", dest="clt_writer", - help="which client writer you wish to use:lua xml json" ) + parser.add_option("-i", "--input", dest="input_path", + default="xls/", + help="read all files from this path") + parser.add_option("-s", "--srv", dest="srv_path", + help="write all server file to this path") + parser.add_option("-c", "--clt", dest="clt_path", + help="write all client file to this path") + parser.add_option("-t", "--timeout", dest="timeout", type="int", + default="-1", + help="only converte files modified within seconds") + parser.add_option("-f", "--suffix", dest="suffix", + default="", + help="what type of file will be readed.empty mean all files") + parser.add_option("-w", "--swriter", dest="srv_writer", + help="which server writer you wish to use:lua xml json") + parser.add_option("-l", "--cwriter", dest="clt_writer", + help="which client writer you wish to use:lua xml json") options, args = parser.parse_args() - reader = Reader( options.input_path,options.srv_path,options.clt_path, - options.timeout,options.suffix,options.srv_writer,options.clt_writer ) + reader = Reader(options.input_path, options.srv_path, options.clt_path, + options.timeout, options.suffix, options.srv_writer, options.clt_writer) reader.attention() - reader.read() \ No newline at end of file + reader.read() diff --git a/src/slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/slpp.py b/src/slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/slpp.py index 7606abd..41a815f 100644 --- a/src/slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/slpp.py +++ b/src/slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/slpp.py @@ -20,6 +20,7 @@ try: except NameError: unicode = str + class ParseError(Exception): pass @@ -40,7 +41,7 @@ class SLPP(object): def decode(self, text): if not text or not isinstance(text, basestring): return - #FIXME: only short comments removed + # FIXME: only short comments removed reg = re.compile('--.*$', re.M) text = reg.sub('', text, 0) self.text = text @@ -71,10 +72,10 @@ class SLPP(object): s += 'nil' elif tp in [list, tuple, dict]: self.depth += 1 - if len(obj) == 0 or ( tp is not dict and len(filter( - lambda x: type(x) in (int, float, long) \ - or (isinstance(x, basestring) and len(x) < 10), obj - )) == len(obj) ): + if len(obj) == 0 or (tp is not dict and len(filter( + lambda x: type(x) in (int, float, long) \ + or (isinstance(x, basestring) and len(x) < 10), obj + )) == len(obj)): newline = tab = '' dp = tab * self.depth s += "%s{%s" % (tab * (self.depth - 2), newline) @@ -117,7 +118,7 @@ class SLPP(object): return self.object() if self.ch == "[": self.next_chr() - if self.ch in ['"', "'", '[']: + if self.ch in ['"', "'", '[']: return self.string(self.ch) if self.ch.isdigit() or self.ch == '-': return self.number() @@ -128,7 +129,7 @@ class SLPP(object): start = self.ch if end == '[': end = ']' - if start in ['"', "'", '[']: + if start in ['"', "'", '[']: while self.next_chr(): if self.ch == end: self.next_chr() @@ -152,7 +153,7 @@ class SLPP(object): if self.ch and self.ch == '}': self.depth -= 1 self.next_chr() - return o #Exit here + return o # Exit here else: while self.ch: self.white() @@ -164,13 +165,14 @@ class SLPP(object): self.depth -= 1 self.next_chr() if k is not None: - o[idx] = k - if not numeric_keys and len([ key for key in o if isinstance(key, (str, unicode, float, bool, tuple))]) == 0: + o[idx] = k + if not numeric_keys and len( + [key for key in o if isinstance(key, (str, unicode, float, bool, tuple))]) == 0: ar = [] for key in o: - ar.insert(key, o[key]) + ar.insert(key, o[key]) o = ar - return o #or here + return o # or here else: if self.ch == ',': self.next_chr() @@ -191,9 +193,10 @@ class SLPP(object): o[idx] = k idx += 1 k = None - raise Exception(ERRORS['unexp_end_table']) #Bad exit here + raise Exception(ERRORS['unexp_end_table']) # Bad exit here words = {'true': True, 'false': False, 'nil': None} + def word(self): s = '' if self.ch != '\n': @@ -211,6 +214,7 @@ class SLPP(object): if not self.ch or not self.ch.isdigit(): raise ParseError(err) return n + n = '' try: if self.ch == '-': @@ -251,7 +255,7 @@ class SLPP(object): def hex(self): n = '' while self.ch and \ - (self.ch in 'ABCDEFabcdef' or self.ch.isdigit()): + (self.ch in 'ABCDEFabcdef' or self.ch.isdigit()): n += self.ch self.next_chr() return n diff --git a/src/slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/tests.py b/src/slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/tests.py index cf4ea27..fe9aff5 100644 --- a/src/slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/tests.py +++ b/src/slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/tests.py @@ -81,8 +81,6 @@ Key: {2}, item: {3}'''.format(value, origin, key, item)) assert value == origin, '{0} not match original: {1}.'.format(value, origin) - - def number_test(): """ Integer and float: @@ -148,6 +146,7 @@ def table_test(): """ pass + def string_test(): r""" Escape test: @@ -158,6 +157,7 @@ def string_test(): """ pass + def basic_test(): """ No data loss: @@ -179,4 +179,5 @@ def unicode_test(): if __name__ == '__main__': import doctest + doctest.testmod() diff --git a/src/slpp/slpp.py b/src/slpp/slpp.py index 7606abd..41a815f 100644 --- a/src/slpp/slpp.py +++ b/src/slpp/slpp.py @@ -20,6 +20,7 @@ try: except NameError: unicode = str + class ParseError(Exception): pass @@ -40,7 +41,7 @@ class SLPP(object): def decode(self, text): if not text or not isinstance(text, basestring): return - #FIXME: only short comments removed + # FIXME: only short comments removed reg = re.compile('--.*$', re.M) text = reg.sub('', text, 0) self.text = text @@ -71,10 +72,10 @@ class SLPP(object): s += 'nil' elif tp in [list, tuple, dict]: self.depth += 1 - if len(obj) == 0 or ( tp is not dict and len(filter( - lambda x: type(x) in (int, float, long) \ - or (isinstance(x, basestring) and len(x) < 10), obj - )) == len(obj) ): + if len(obj) == 0 or (tp is not dict and len(filter( + lambda x: type(x) in (int, float, long) \ + or (isinstance(x, basestring) and len(x) < 10), obj + )) == len(obj)): newline = tab = '' dp = tab * self.depth s += "%s{%s" % (tab * (self.depth - 2), newline) @@ -117,7 +118,7 @@ class SLPP(object): return self.object() if self.ch == "[": self.next_chr() - if self.ch in ['"', "'", '[']: + if self.ch in ['"', "'", '[']: return self.string(self.ch) if self.ch.isdigit() or self.ch == '-': return self.number() @@ -128,7 +129,7 @@ class SLPP(object): start = self.ch if end == '[': end = ']' - if start in ['"', "'", '[']: + if start in ['"', "'", '[']: while self.next_chr(): if self.ch == end: self.next_chr() @@ -152,7 +153,7 @@ class SLPP(object): if self.ch and self.ch == '}': self.depth -= 1 self.next_chr() - return o #Exit here + return o # Exit here else: while self.ch: self.white() @@ -164,13 +165,14 @@ class SLPP(object): self.depth -= 1 self.next_chr() if k is not None: - o[idx] = k - if not numeric_keys and len([ key for key in o if isinstance(key, (str, unicode, float, bool, tuple))]) == 0: + o[idx] = k + if not numeric_keys and len( + [key for key in o if isinstance(key, (str, unicode, float, bool, tuple))]) == 0: ar = [] for key in o: - ar.insert(key, o[key]) + ar.insert(key, o[key]) o = ar - return o #or here + return o # or here else: if self.ch == ',': self.next_chr() @@ -191,9 +193,10 @@ class SLPP(object): o[idx] = k idx += 1 k = None - raise Exception(ERRORS['unexp_end_table']) #Bad exit here + raise Exception(ERRORS['unexp_end_table']) # Bad exit here words = {'true': True, 'false': False, 'nil': None} + def word(self): s = '' if self.ch != '\n': @@ -211,6 +214,7 @@ class SLPP(object): if not self.ch or not self.ch.isdigit(): raise ParseError(err) return n + n = '' try: if self.ch == '-': @@ -251,7 +255,7 @@ class SLPP(object): def hex(self): n = '' while self.ch and \ - (self.ch in 'ABCDEFabcdef' or self.ch.isdigit()): + (self.ch in 'ABCDEFabcdef' or self.ch.isdigit()): n += self.ch self.next_chr() return n diff --git a/src/slpp/tests.py b/src/slpp/tests.py index 31b63e9..13bca18 100644 --- a/src/slpp/tests.py +++ b/src/slpp/tests.py @@ -81,8 +81,6 @@ Key: {2}, item: {3}'''.format(value, origin, key, item)) assert value == origin, '{0} not match original: {1}.'.format(value, origin) - - def number_test(): """ Integer and float: @@ -148,6 +146,7 @@ def table_test(): """ pass + def string_test(): r""" Escape test: @@ -158,6 +157,7 @@ def string_test(): """ pass + def basic_test(): """ No data loss: @@ -179,4 +179,5 @@ def unicode_test(): if __name__ == '__main__': import doctest + doctest.testmod() diff --git a/src/writer.py b/src/writer.py index 52e6ed8..1f94f5f 100644 --- a/src/writer.py +++ b/src/writer.py @@ -1,11 +1,6 @@ #! python # -*- coding:utf-8 -*- -import os -import sys -import json -from xml.dom.minidom import Document - try: basestring except NameError: @@ -27,31 +22,35 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class Writer(object): - def __init__(self,doc_name,sheet_name, base_name, keys_list, comment_text, is_list): + def __init__(self, doc_name, sheet_name, base_name, keys_list, comment_text, is_list): # 鏂囦欢鍚嶅寘鍚腑鏂囧垯闇瑕佽浆unicode - #self.doc_name = unicode(doc_name, "utf-8") - self.doc_name = doc_name + # self.doc_name = unicode(doc_name, "utf-8") + self.doc_name = doc_name self.sheet_name = sheet_name - self.base_name = base_name - self.keys_list = keys_list - self.comment_text = comment_text + self.base_name = base_name + self.keys_list = keys_list + self.comment_text = comment_text self.is_list = is_list # 鏂囦欢鍚庣紑 def suffix(self): pass + # 鏂囦欢鍐呭 - def context(self,ctx): + def context(self, ctx): pass + # 娉ㄩ噴寮濮 def comment_start(self): pass + # 娉ㄩ噴缁撴潫 def comment_end(self): pass + # 鏂囦欢娉ㄩ噴(鍗冧竾涓嶈鍔犳椂闂达紝褰卞搷svn) def comment(self): comment = [] - return "".join( comment ) - + return "".join(comment) diff --git a/src/writer_elixir.py b/src/writer_elixir.py index 6d05d39..b5b55b2 100644 --- a/src/writer_elixir.py +++ b/src/writer_elixir.py @@ -1,8 +1,6 @@ #! python # -*- coding:utf-8 -*- -import os -import sys from writer import * try: @@ -26,6 +24,7 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class ElixirWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): @@ -39,42 +38,42 @@ class ElixirWriter(Writer): '\ndefmodule ' + self.base_name.title() + ' do\n\n' ] - return "\n".join( comment ) + return "\n".join(comment) # 鑾峰彇缂╄繘瀛楃涓 - def indent_ctx( self,indent ): + def indent_ctx(self, indent): if indent <= 0: return "" if indent not in INDENT_LIST: INDENT_LIST[indent] = "" else: - ctx = BASE_INDENT*indent + ctx = BASE_INDENT * indent INDENT_LIST[indent] = ctx return INDENT_LIST[indent] - def dict_to_text(self, value, indent) : + def dict_to_text(self, value, indent): dict_text_list = [] - for k in ( value ) : - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + for k in (value): + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) comment = self.comment_text[k] - val_type = type( lk ) - if str == val_type : - if lk.replace(".", "").isdigit() : + val_type = type(lk) + if str == val_type: + if lk.replace(".", "").isdigit(): lk.replace("\"", "") - else : + else: lk = ':' + lk.replace("\"", "") - key = "".join( [" def get(",lk,") do\n"] ) + key = "".join([" def get(", lk, ") do\n"]) - val = "".join( [" ## ", comment, "\n", key, " ", lv, "\n end\n\n"] ) + val = "".join([" ## ", comment, "\n", key, " ", lv, "\n end\n\n"]) - dict_text_list.append( val ) + dict_text_list.append(val) - dict_str = "".join( dict_text_list ) + dict_str = "".join(dict_text_list) dict_str = dict_str + " def get(_) do\n :undefined\n end\n\nend" return False, dict_str @@ -84,78 +83,78 @@ class ElixirWriter(Writer): struct_text_list = [] struct_len = len(self.comment_text) tem_count = 0 - for k in self.comment_text : + for k in self.comment_text: tem_count += 1 comment = self.comment_text[k] - k_indent,lk = self.to_target_lang( k,indent ) - val_type = type( lk ) - if str == val_type : - if lk.replace(".", "").isdigit() : + k_indent, lk = self.to_target_lang(k, indent) + val_type = type(lk) + if str == val_type: + if lk.replace(".", "").isdigit(): lk.replace("\"", "") - else : + else: lk = ':' + lk.replace("\"", "") - if tem_count != struct_len : + if tem_count != struct_len: lk = lk + ',' - else : + else: lk = lk - if None == comment : + if None == comment: comment = "" - val = "".join( [lk.ljust(20, " "), "\t## ", comment, "\n"] ) + val = "".join([lk.ljust(20, " "), "\t## ", comment, "\n"]) - struct_text_list.append( val ) + struct_text_list.append(val) - struct_str = " ".join( struct_text_list ) + struct_str = " ".join(struct_text_list) end_str = " defstruct [\n " + struct_str + " ]\n\n" list_text_list.append(end_str) all_key_list = [] # 鐢熸垚 get() 鍑芥暟 - for i, onedict in enumerate( value ) : + for i, onedict in enumerate(value): # 鐢熸垚瀵瑰簲鐨 key key_list = [] - for k in ( onedict ) : - if None != self.keys_list.get(k, None) : - is_indent,lv = self.to_target_lang( onedict[k],indent + 1 ) + for k in (onedict): + if None != self.keys_list.get(k, None): + is_indent, lv = self.to_target_lang(onedict[k], indent + 1) key_list.append(lv) all_key_list.append(key_list) - tem = ", ".join( key_list ) + tem = ", ".join(key_list) - key = "".join( [" def get(",tem,") do\n %", self.base_name.title(), "{\n "] ) + key = "".join([" def get(", tem, ") do\n %", self.base_name.title(), "{\n "]) # 鐢熸垚瀵瑰簲鐨剉alue value_list = [] onedict_len = len(onedict) tem_count = 0 - for k in ( onedict ) : + for k in (onedict): tem_count += 1 - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( onedict[k],indent + 1 ) + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(onedict[k], indent + 1) - val_type = type( lk ) - if str == val_type : - if lk.replace(".", "").isdigit() : + val_type = type(lk) + if str == val_type: + if lk.replace(".", "").isdigit(): lk.replace("\"", "") - else : + else: lk = ':' + lk.replace("\"", "") - if tem_count != onedict_len : - oneval = "".join( [lk, " => ", lv , ",\n"] ) - value_list.append( oneval ) - else : - oneval = "".join( [lk, " => ", lv , "\n"] ) - value_list.append( oneval ) + if tem_count != onedict_len: + oneval = "".join([lk, " => ", lv, ",\n"]) + value_list.append(oneval) + else: + oneval = "".join([lk, " => ", lv, "\n"]) + value_list.append(oneval) value_list_str = " ".join(value_list) - end_str = "".join( [key, value_list_str, " }\n end\n\n"] ) + end_str = "".join([key, value_list_str, " }\n end\n\n"]) - list_text_list.append( end_str ) + list_text_list.append(end_str) underline_list = [] - for i in self.keys_list : + for i in self.keys_list: underline_list.append('_') end_str = ", ".join(underline_list) @@ -167,153 +166,151 @@ class ElixirWriter(Writer): get_all_fun = [] allkey_len = len(all_key_list) tem_count = 0 - for i, ival in enumerate(all_key_list) : + for i, ival in enumerate(all_key_list): tem_count += 1 - if tem_count != allkey_len : + if tem_count != allkey_len: oneval = '{' + ", ".join(ival) + '},\n' get_all_fun.append(oneval) - else : + else: oneval = '{' + ", ".join(ival) + '}\n' get_all_fun.append(oneval) value_list_str = " ".join(get_all_fun) start_str = ' def get_all() do\n [\n ' - end_str = "".join( [start_str, value_list_str, " ]\n end\n\n"] ) + end_str = "".join([start_str, value_list_str, " ]\n end\n\n"]) - list_text_list.append( end_str ) + list_text_list.append(end_str) # 鐢熸垚 get_list() 鍑芥暟 get_list_fun = [] keys_len = len(self.keys_list) - for key in self.keys_list : + for key in self.keys_list: keyindex = self.keys_list[key] - if keyindex == 1 : - list_text_list.append( ' def get_list() do\n get_all()\n end\n\n') - elif keyindex <= keys_len : + if keyindex == 1: + list_text_list.append(' def get_list() do\n get_all()\n end\n\n') + elif keyindex <= keys_len: get_tem_dict = {} underline_list = [] - for i, ival in enumerate(all_key_list) : + for i, ival in enumerate(all_key_list): key_tem_list = [] j = 0 underline_list = [] - while j < keyindex - 1 : + while j < keyindex - 1: key_tem_list.append(ival[j]) underline_list.append('_') j += 1 keystr = '(' + ", ".join(key_tem_list) + ')' - if None != get_tem_dict.get(keystr, None) : + if None != get_tem_dict.get(keystr, None): oldlist = get_tem_dict[keystr] oldlist.append(ival) get_tem_dict[keystr] = oldlist - else : + else: get_tem_dict[keystr] = [ival] - for onekey in get_tem_dict : + for onekey in get_tem_dict: value_tem_list = [] valuelist = get_tem_dict[onekey] value_len = len(valuelist) tem_count = 0 - for l, lval in enumerate(valuelist) : + for l, lval in enumerate(valuelist): tem_count += 1 - if tem_count != value_len : + if tem_count != value_len: oneval = '{' + ", ".join(lval) + '},\n' value_tem_list.append(oneval) - else : + else: oneval = '{' + ", ".join(lval) + '}\n' value_tem_list.append(oneval) start_str = ' def get_list' + onekey + ' do\n [\n ' - end_str = "".join( [start_str, " ".join(value_tem_list), " ]\n end\n\n"] ) + end_str = "".join([start_str, " ".join(value_tem_list), " ]\n end\n\n"]) get_list_fun.append(end_str) - no_match_str = "".join(' def get_list(' + ", ".join(underline_list) + ') do\n []\n end\n\n') + no_match_str = "".join( + ' def get_list(' + ", ".join(underline_list) + ') do\n []\n end\n\n') get_list_fun.append(no_match_str) - value_list_str = "".join(get_list_fun) + 'end' - list_text_list.append( value_list_str ) - dict_str = "".join( list_text_list ) + list_text_list.append(value_list_str) + dict_str = "".join(list_text_list) return False, dict_str # 杞崲涓烘枃鏈暟鎹 涔嬪墠瑙f瀽鍑烘潵鐨別xcel鏁版嵁瀛樻斁鏂瑰紡瀛樺湪LIST(array鏍煎紡)鍜孌ICT(object鏍煎紡)涓ょ绫诲瀷 - def to_text(self,value,indent): - val_type = type( value ) - if dict == val_type : - return self.dict_to_text(value, indent) - else : - return self.list_to_text(value, indent) + def to_text(self, value, indent): + val_type = type(value) + if dict == val_type: + return self.dict_to_text(value, indent) + else: + return self.list_to_text(value, indent) # python鐨刣ict杞崲涓篹lixir鐨刴ap绫诲瀷 - def dict_to_elixir(self,value,indent): + def dict_to_elixir(self, value, indent): dict_ctx_list = [] - for k in ( value ) : - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + for k in (value): + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) - val_type = type( lk ) - if str == val_type : - if lk.replace(".", "").isdigit() : + val_type = type(lk) + if str == val_type: + if lk.replace(".", "").isdigit(): lk.replace("\"", "") - else : + else: lk = ':' + lk.replace("\"", "") - key = "".join( [lk," => "] ) - val = "".join( [key, lv] ) + key = "".join([lk, " => "]) + val = "".join([key, lv]) dict_ctx_list.append(val) - dict_str = ", ".join( dict_ctx_list ) - return False,"".join( ["%{",dict_str,"}"] ) + dict_str = ", ".join(dict_ctx_list) + return False, "".join(["%{", dict_str, "}"]) # python鐨刲ist杞崲涓篹lixir鐨刲ist绫诲瀷 - def list_to_elixir(self,value,indent): + def list_to_elixir(self, value, indent): list_ctx_list = [] - for v in value : - is_indent,lv = self.to_target_lang( v,indent + 1 ) - list_ctx_list.append( lv ) + for v in value: + is_indent, lv = self.to_target_lang(v, indent + 1) + list_ctx_list.append(lv) - - list_str = ", ".join( list_ctx_list ) - return False,"".join( ["[",list_str,"]"] ) + list_str = ", ".join(list_ctx_list) + return False, "".join(["[", list_str, "]"]) # python鐨則uple杞崲涓篹lixir鐨則uple绫诲瀷 - def tuple_to_elixir(self,value,indent): + def tuple_to_elixir(self, value, indent): tuple_ctx_list = [] - for v in value : - is_indent,lv = self.to_target_lang( v,indent + 1 ) - tuple_ctx_list.append( lv ) + for v in value: + is_indent, lv = self.to_target_lang(v, indent + 1) + tuple_ctx_list.append(lv) # 杩斿洖 {a,b,c}杩欑涓嶆崲琛岀殑鏍煎紡 - list_str = ", ".join( tuple_ctx_list ) - return False,"".join( ["{",list_str,"}"] ) - + list_str = ", ".join(tuple_ctx_list) + return False, "".join(["{", list_str, "}"]) # 鍙橀噺杞崲鍒扮洰鏍囪瑷瀛楃涓 - def to_target_lang(self,value,indent): - val_type = type( value ) - if int == val_type : - return False,str( value ) - elif long == val_type : - return False,str( value ) - elif float == val_type : + def to_target_lang(self, value, indent): + val_type = type(value) + if int == val_type: + return False, str(value) + elif long == val_type: + return False, str(value) + elif float == val_type: # 1001.0 -->> 001 鍘婚櫎澶氫綑灏忔暟鐐 - if int( value ) == value : - return False,str( int(value) ) - return False,str( value ) + if int(value) == value: + return False, str(int(value)) + return False, str(value) elif str == val_type or unicode == val_type: - return False, "".join(["\"",value,"\""]) - elif tuple == val_type : - return self.tuple_to_elixir(value,indent) - elif dict == val_type : - return self.dict_to_elixir(value,indent) - elif list == val_type : - return self.list_to_elixir(value,indent) - else : - raise Exception( "invalid type",val_type ) - - #鏂囦欢鍐呭 - def context(self,ctx): - is_indent,str_ctx = self.to_text( ctx,0 ) - return "".join( [self.comment(),"",str_ctx] ) + return False, "".join(["\"", value, "\""]) + elif tuple == val_type: + return self.tuple_to_elixir(value, indent) + elif dict == val_type: + return self.dict_to_elixir(value, indent) + elif list == val_type: + return self.list_to_elixir(value, indent) + else: + raise Exception("invalid type", val_type) + + # 鏂囦欢鍐呭 + def context(self, ctx): + is_indent, str_ctx = self.to_text(ctx, 0) + return "".join([self.comment(), "", str_ctx]) diff --git a/src/writer_erlang_erl.py b/src/writer_erlang_erl.py index eda1680..b1d4b33 100644 --- a/src/writer_erlang_erl.py +++ b/src/writer_erlang_erl.py @@ -1,8 +1,6 @@ #! python # -*- coding:utf-8 -*- -import os -import sys from writer import * try: @@ -26,6 +24,7 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class ErlangerlWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): @@ -40,41 +39,41 @@ class ErlangerlWriter(Writer): '\n' ] - return "\n".join( comment ) + return "\n".join(comment) # 鑾峰彇缂╄繘瀛楃涓 - def indent_ctx( self,indent ): + def indent_ctx(self, indent): if indent <= 0: return "" if indent not in INDENT_LIST: INDENT_LIST[indent] = "" else: - ctx = BASE_INDENT*indent + ctx = BASE_INDENT * indent INDENT_LIST[indent] = ctx return INDENT_LIST[indent] - def dict_to_text(self, value, indent) : + def dict_to_text(self, value, indent): dict_text_list = [] dict_text_list.append("-compile([export_all, nowarn_export_all]).\n\n") - for k in ( value ) : - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + for k in (value): + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) comment = self.comment_text[k] - val_type = type( lk ) - if str == val_type : + val_type = type(lk) + if str == val_type: lk = lk.replace("<<\"", "\'") lk = lk.replace("\"/utf8>>", "\'") - key = "".join( ["get(",lk,") ->\n"] ) + key = "".join(["get(", lk, ") ->\n"]) - val = "".join( ["%% ", comment, "\n", key, " ", lv, ";\n\n"] ) + val = "".join(["%% ", comment, "\n", key, " ", lv, ";\n\n"]) - dict_text_list.append( val ) + dict_text_list.append(val) - dict_str = "".join( dict_text_list ) + dict_str = "".join(dict_text_list) dict_str = dict_str + "get(_) ->\n undefined." return False, dict_str @@ -84,41 +83,41 @@ class ErlangerlWriter(Writer): list_text_list.append(val) all_key_list = [] # 鐢熸垚 get() 鍑芥暟 - for i, onedict in enumerate( value ) : + for i, onedict in enumerate(value): # 鐢熸垚瀵瑰簲鐨 key key_list = [] - for k in ( onedict ) : - if None != self.keys_list.get(k, None) : - is_indent,lv = self.to_target_lang( onedict[k],indent + 1 ) + for k in (onedict): + if None != self.keys_list.get(k, None): + is_indent, lv = self.to_target_lang(onedict[k], indent + 1) key_list.append(lv) all_key_list.append(key_list) - tem = ", ".join( key_list ) + tem = ", ".join(key_list) - key = "".join( ["get(",tem,") ->\n #", self.base_name, "{\n "] ) + key = "".join(["get(", tem, ") ->\n #", self.base_name, "{\n "]) # 鐢熸垚瀵瑰簲鐨剉alue value_list = [] - for k in ( onedict ) : - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( onedict[k],indent + 1 ) + for k in (onedict): + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(onedict[k], indent + 1) - val_type = type( lk ) - if str == val_type : + val_type = type(lk) + if str == val_type: lk = lk.replace("<<\"", "\'") lk = lk.replace("\"/utf8>>", "\'") - oneval = "".join( [lk, " = ", lv , "\n"] ) + oneval = "".join([lk, " = ", lv, "\n"]) - value_list.append( oneval ) + value_list.append(oneval) value_list_str = " , ".join(value_list) - end_str = "".join( [key, value_list_str, "};\n\n"] ) + end_str = "".join([key, value_list_str, "};\n\n"]) - list_text_list.append( end_str ) + list_text_list.append(end_str) underline_list = [] - for i in self.keys_list : + for i in self.keys_list: underline_list.append('_') end_str = ", ".join(underline_list) @@ -128,134 +127,133 @@ class ErlangerlWriter(Writer): # 鐢熸垚 get_all() 鍑芥暟 get_all_fun = [] - for i, ival in enumerate(all_key_list) : + for i, ival in enumerate(all_key_list): oneval = '{' + ", ".join(ival) + '}\n' get_all_fun.append(oneval) value_list_str = " , ".join(get_all_fun) start_str = 'getList() ->\n [\n ' - end_str = "".join( [start_str, value_list_str, " ].\n\n"] ) + end_str = "".join([start_str, value_list_str, " ].\n\n"]) # 鐢熸垚 get_list() 鍑芥暟 get_list_fun = [] keys_len = len(self.keys_list) - for key in self.keys_list : + for key in self.keys_list: keyindex = self.keys_list[key] - if keyindex == 1 : + if keyindex == 1: "skip" - elif keyindex <= keys_len : + elif keyindex <= keys_len: get_tem_dict = {} underline_list = [] - for i, ival in enumerate(all_key_list) : + for i, ival in enumerate(all_key_list): key_tem_list = [] j = 0 underline_list = [] - while j < keyindex - 1 : + while j < keyindex - 1: key_tem_list.append(ival[j]) underline_list.append('_') j += 1 keystr = '(' + ", ".join(key_tem_list) + ')' - if None != get_tem_dict.get(keystr, None) : + if None != get_tem_dict.get(keystr, None): oldlist = get_tem_dict[keystr] oldlist.append(ival) get_tem_dict[keystr] = oldlist - else : + else: get_tem_dict[keystr] = [ival] - for onekey in get_tem_dict : + for onekey in get_tem_dict: value_tem_list = [] valuelist = get_tem_dict[onekey] - for l, lval in enumerate(valuelist) : + for l, lval in enumerate(valuelist): oneval = '{' + ", ".join(lval) + '}\n' value_tem_list.append(oneval) start = 'getList' + onekey + ' ->\n [\n ' - val = "".join( [start, " , ".join(value_tem_list), " ];\n\n"] ) + val = "".join([start, " , ".join(value_tem_list), " ];\n\n"]) get_list_fun.append(val) no_match_str = "".join('getList(' + ", ".join(underline_list) + ') ->\n [].\n\n') get_list_fun.append(no_match_str) if self.is_list == True: value_list = "".join(get_list_fun) - list_text_list.append( end_str ) - list_text_list.append( value_list ) - dict_str = "".join( list_text_list ) + list_text_list.append(end_str) + list_text_list.append(value_list) + dict_str = "".join(list_text_list) return False, dict_str # 杞崲涓烘枃鏈暟鎹 涔嬪墠瑙f瀽鍑烘潵鐨別xcel鏁版嵁瀛樻斁鏂瑰紡瀛樺湪LIST(array鏍煎紡)鍜孌ICT(object鏍煎紡)涓ょ绫诲瀷 - def to_text(self,value,indent): - val_type = type( value ) - if dict == val_type : - return self.dict_to_text(value, indent) - else : - return self.list_to_text(value, indent) + def to_text(self, value, indent): + val_type = type(value) + if dict == val_type: + return self.dict_to_text(value, indent) + else: + return self.list_to_text(value, indent) # python鐨刣ict杞崲涓篹rlang鐨刴ap绫诲瀷 - def dict_to_erlang(self,value,indent): + def dict_to_erlang(self, value, indent): dict_ctx_list = [] - for k in ( value ) : - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + for k in (value): + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) - val_type = type( lk ) - if str == val_type : + val_type = type(lk) + if str == val_type: lk = lk.replace("<<\"", "\'") lk = lk.replace("\"/utf8>>", "\'") - key = "".join( [lk," => "] ) - val = "".join( [key, lv] ) + key = "".join([lk, " => "]) + val = "".join([key, lv]) dict_ctx_list.append(val) - dict_str = ", ".join( dict_ctx_list ) - return False,"".join( ["#{",dict_str,"}"] ) + dict_str = ", ".join(dict_ctx_list) + return False, "".join(["#{", dict_str, "}"]) # python鐨刲ist杞崲涓篹rlang鐨刲ist绫诲瀷 - def list_to_erlang(self,value,indent): + def list_to_erlang(self, value, indent): list_ctx_list = [] - for v in value : - is_indent,lv = self.to_target_lang( v,indent + 1 ) - list_ctx_list.append( lv ) + for v in value: + is_indent, lv = self.to_target_lang(v, indent + 1) + list_ctx_list.append(lv) - list_str = ", ".join( list_ctx_list ) - return False,"".join( ["[",list_str,"]"] ) + list_str = ", ".join(list_ctx_list) + return False, "".join(["[", list_str, "]"]) # python鐨則uple杞崲涓篹rlang鐨則uple绫诲瀷 - def tuple_to_erlang(self,value,indent): + def tuple_to_erlang(self, value, indent): tuple_ctx_list = [] - for v in value : - is_indent,lv = self.to_target_lang( v,indent + 1 ) - tuple_ctx_list.append( lv ) + for v in value: + is_indent, lv = self.to_target_lang(v, indent + 1) + tuple_ctx_list.append(lv) # 杩斿洖 {a,b,c}杩欑涓嶆崲琛岀殑鏍煎紡 - list_str = ", ".join( tuple_ctx_list ) - return False,"".join( ["{",list_str,"}"] ) - + list_str = ", ".join(tuple_ctx_list) + return False, "".join(["{", list_str, "}"]) # 鍙橀噺杞崲鍒扮洰鏍囪瑷鐨勫瓧绗︿覆 - def to_target_lang(self,value,indent): - val_type = type( value ) - if int == val_type : - return False,str( value ) - elif long == val_type : - return False,str( value ) - elif float == val_type : + def to_target_lang(self, value, indent): + val_type = type(value) + if int == val_type: + return False, str(value) + elif long == val_type: + return False, str(value) + elif float == val_type: # 1001.0 -->> 001 鍘婚櫎澶氫綑灏忔暟鐐 - if int( value ) == value : - return False,str( int(value) ) - return False,str( value ) + if int(value) == value: + return False, str(int(value)) + return False, str(value) elif str == val_type or unicode == val_type: - return False, "".join(["<<\"",value,"\"/utf8>>"]) - elif tuple == val_type : - return self.tuple_to_erlang(value,indent) - elif dict == val_type : - return self.dict_to_erlang(value,indent) - elif list == val_type : - return self.list_to_erlang(value,indent) - else : - raise Exception( "invalid type",val_type ) - - #鏂囦欢鍐呭 - def context(self,ctx): - is_indent,str_ctx = self.to_text( ctx,0 ) - return "".join( [self.comment(),"",str_ctx] ) + return False, "".join(["<<\"", value, "\"/utf8>>"]) + elif tuple == val_type: + return self.tuple_to_erlang(value, indent) + elif dict == val_type: + return self.dict_to_erlang(value, indent) + elif list == val_type: + return self.list_to_erlang(value, indent) + else: + raise Exception("invalid type", val_type) + + # 鏂囦欢鍐呭 + def context(self, ctx): + is_indent, str_ctx = self.to_text(ctx, 0) + return "".join([self.comment(), "", str_ctx]) diff --git a/src/writer_erlang_hrl.py b/src/writer_erlang_hrl.py index b2522cf..ce6db05 100644 --- a/src/writer_erlang_hrl.py +++ b/src/writer_erlang_hrl.py @@ -1,8 +1,6 @@ #! python # -*- coding:utf-8 -*- -import os -import sys from writer import * try: @@ -26,6 +24,7 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class ErlanghrlWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): @@ -33,120 +32,119 @@ class ErlanghrlWriter(Writer): def comment(self): comment = [ - '%% Automatic generation from -->>' + '%% Automatic generation from -->>' '\n%% excel file name : ' + self.doc_name + '\n%% excel sheet name : ' + self.sheet_name, '\n-record(' + self.base_name + ', {\n ' ] - return "\n".join( comment ) + return "\n".join(comment) # 鑾峰彇缂╄繘瀛楃涓 - def indent_ctx( self,indent ) : + def indent_ctx(self, indent): if indent <= 0: return "" - if indent not in INDENT_LIST : + if indent not in INDENT_LIST: INDENT_LIST[indent] = "" - else : - ctx = BASE_INDENT*indent + else: + ctx = BASE_INDENT * indent INDENT_LIST[indent] = ctx return INDENT_LIST[indent] def list_to_text(self, value, indent): list_text_list = [] - for k in self.comment_text : + for k in self.comment_text: comment = self.comment_text[k] - k_indent,lk = self.to_target_lang( k,indent ) - val_type = type( lk ) - if str == val_type : + k_indent, lk = self.to_target_lang(k, indent) + val_type = type(lk) + if str == val_type: lk = lk.replace("\"", "\'") - if None == comment : + if None == comment: comment = "" - val = "".join( [lk.ljust(20, " "), "\t%% ", comment, "\n"] ) + val = "".join([lk.ljust(20, " "), "\t%% ", comment, "\n"]) - list_text_list.append( val ) + list_text_list.append(val) - list_str = " , ".join( list_text_list ) + list_str = " , ".join(list_text_list) list_str = list_str + "})." return False, list_str # 杞崲涓烘枃鏈暟鎹 涔嬪墠瑙f瀽鍑烘潵鐨別xcel鏁版嵁瀛樻斁鏂瑰紡瀛樺湪LIST(array鏍煎紡)鍜孌ICT(object鏍煎紡)涓ょ绫诲瀷 - def to_text(self,value,indent): - val_type = type( value ) - if list == val_type : - return self.list_to_text(value, indent) - else : + def to_text(self, value, indent): + val_type = type(value) + if list == val_type: + return self.list_to_text(value, indent) + else: return False, None # python鐨刣ict杞崲涓篹rlang鐨刴ap绫诲瀷 - def dict_to_erlang(self,value,indent): + def dict_to_erlang(self, value, indent): dict_ctx_list = [] - for k in ( value ) : - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + for k in (value): + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) - val_type = type( lk ) - if str == val_type : + val_type = type(lk) + if str == val_type: lk = lk.replace("\"", "\'") - key = "".join( [lk," => "] ) - val = "".join( [key, lv] ) + key = "".join([lk, " => "]) + val = "".join([key, lv]) dict_ctx_list.append(val) - dict_str = ",".join( dict_ctx_list ) - return False,"".join( ["#{",dict_str,"}"] ) + dict_str = ",".join(dict_ctx_list) + return False, "".join(["#{", dict_str, "}"]) # python鐨刲ist杞崲涓篹rlang鐨刲ist绫诲瀷 - def list_to_erlang(self,value,indent): + def list_to_erlang(self, value, indent): list_ctx_list = [] - for v in value : - is_indent,lv = self.to_target_lang( v,indent + 1 ) - list_ctx_list.append( lv ) - + for v in value: + is_indent, lv = self.to_target_lang(v, indent + 1) + list_ctx_list.append(lv) - list_str = ",".join( list_ctx_list ) - return False,"".join( ["[",list_str,"]"] ) + list_str = ",".join(list_ctx_list) + return False, "".join(["[", list_str, "]"]) # python鐨則uple杞崲涓篹rlang鐨則uple绫诲瀷 - def tuple_to_erlang(self,value,indent): + def tuple_to_erlang(self, value, indent): tuple_ctx_list = [] - for v in value : - is_indent,lv = self.to_target_lang( v,indent + 1 ) - tuple_ctx_list.append( lv ) + for v in value: + is_indent, lv = self.to_target_lang(v, indent + 1) + tuple_ctx_list.append(lv) # 杩斿洖 {a,b,c}杩欑涓嶆崲琛岀殑鏍煎紡 - list_str = ",".join( tuple_ctx_list ) - return False,"".join( ["{",list_str,"}"] ) + list_str = ",".join(tuple_ctx_list) + return False, "".join(["{", list_str, "}"]) # 鍙橀噺杞崲鍒扮洰鏍囪瑷鐨勫瓧绗︿覆 - def to_target_lang(self,value,indent): - val_type = type( value ) - if int == val_type : - return False,str( value ) - elif long == val_type : - return False,str( value ) - elif float == val_type : + def to_target_lang(self, value, indent): + val_type = type(value) + if int == val_type: + return False, str(value) + elif long == val_type: + return False, str(value) + elif float == val_type: # 1001.0 -->> 001 鍘婚櫎澶氫綑灏忔暟鐐 - if int( value ) == value : - return False,str( int(value) ) - return False,str( value ) + if int(value) == value: + return False, str(int(value)) + return False, str(value) elif str == val_type or unicode == val_type: - return False, "".join(["\"",value,"\""]) - elif tuple == val_type : - return self.tuple_to_erlang(value,indent) - elif dict == val_type : - return self.dict_to_erlang(value,indent) - elif list == val_type : - return self.list_to_erlang(value,indent) - else : - raise Exception( "invalid type",val_type ) - - #鏂囦欢鍐呭 - def context(self,ctx): - is_indent,str_ctx = self.to_text( ctx,0 ) - if None != str_ctx : - return "".join( [self.comment(),"",str_ctx] ) - else : + return False, "".join(["\"", value, "\""]) + elif tuple == val_type: + return self.tuple_to_erlang(value, indent) + elif dict == val_type: + return self.dict_to_erlang(value, indent) + elif list == val_type: + return self.list_to_erlang(value, indent) + else: + raise Exception("invalid type", val_type) + + # 鏂囦欢鍐呭 + def context(self, ctx): + is_indent, str_ctx = self.to_text(ctx, 0) + if None != str_ctx: + return "".join([self.comment(), "", str_ctx]) + else: return None diff --git a/src/writer_json_array.py b/src/writer_json_array.py index 0c5fabe..63694f2 100644 --- a/src/writer_json_array.py +++ b/src/writer_json_array.py @@ -1,9 +1,8 @@ #! python # -*- coding:utf-8 -*- -import os -import sys import json + from writer import * try: @@ -27,15 +26,13 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class JsonarrayWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): return ".json" # 鏂囦欢鍐呭(瀛楃涓) - def context(self,ctx): - return json.dumps(ctx,ensure_ascii=False,\ - indent=4,sort_keys=True,separators=(',', ':') ) - - - + def context(self, ctx): + return json.dumps(ctx, ensure_ascii=False, \ + indent=4, sort_keys=True, separators=(',', ':')) diff --git a/src/writer_json_object.py b/src/writer_json_object.py index ba887f0..6e5e64e 100644 --- a/src/writer_json_object.py +++ b/src/writer_json_object.py @@ -1,8 +1,6 @@ #! python # -*- coding:utf-8 -*- -import os -import sys from writer import * try: @@ -26,6 +24,7 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class JsonobjectWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): @@ -33,41 +32,41 @@ class JsonobjectWriter(Writer): def comment(self): comment = [] - return "\n".join( comment ) + return "\n".join(comment) # 鑾峰彇缂╄繘瀛楃涓 - def indent_ctx( self,indent ): + def indent_ctx(self, indent): if indent <= 0: return "" if indent not in INDENT_LIST: - ctx = BASE_INDENT*indent + ctx = BASE_INDENT * indent INDENT_LIST[indent] = ctx return INDENT_LIST[indent] - def dict_to_text(self, value, indent) : + def dict_to_text(self, value, indent): dict_ctx_list = [] - is_indent,lv = self.to_target_lang( value, indent) + is_indent, lv = self.to_target_lang(value, indent) dict_ctx_list.append(lv) - dict_str = "".join( dict_ctx_list ) + dict_str = "".join(dict_ctx_list) - return False,"".join( [dict_str] ) + return False, "".join([dict_str]) - def list_to_dit(self, cur_key_index, total_key_cnt, onedict, storge_dict) : - for k in ( onedict ) : + def list_to_dit(self, cur_key_index, total_key_cnt, onedict, storge_dict): + for k in (onedict): key_index = self.keys_list.get(k, None) - if None != key_index and key_index == cur_key_index : + if None != key_index and key_index == cur_key_index: lv = onedict[k] - if cur_key_index == total_key_cnt : + if cur_key_index == total_key_cnt: storge_dict[lv] = onedict - else : - if None != storge_dict.get(lv, None) : + else: + if None != storge_dict.get(lv, None): olddict = storge_dict[lv] new_storge_dict = olddict self.list_to_dit(cur_key_index + 1, total_key_cnt, onedict, new_storge_dict) - else : - storge_dict[lv] ={} + else: + storge_dict[lv] = {} new_storge_dict = storge_dict[lv] self.list_to_dit(cur_key_index + 1, total_key_cnt, onedict, new_storge_dict) @@ -77,77 +76,76 @@ class JsonobjectWriter(Writer): ## 澶勭悊澶氫釜key鐨勬儏鍐 key_value_list = {} key_cnt = len(self.keys_list) - for i, onedict in enumerate( value ) : + for i, onedict in enumerate(value): self.list_to_dit(1, key_cnt, onedict, key_value_list) - is_indent,lv = self.to_target_lang( key_value_list, 0 ) - list_str = "".join( lv ) + is_indent, lv = self.to_target_lang(key_value_list, 0) + list_str = "".join(lv) list_text_list.append(list_str) - return False,"".join( list_text_list ) + return False, "".join(list_text_list) # 杞崲涓烘枃鏈暟鎹 涔嬪墠瑙f瀽鍑烘潵鐨別xcel鏁版嵁瀛樻斁鏂瑰紡瀛樺湪LIST(array鏍煎紡)鍜孌ICT(object鏍煎紡)涓ょ绫诲瀷 - def to_text(self,value,indent): - val_type = type( value ) - if dict == val_type : + def to_text(self, value, indent): + val_type = type(value) + if dict == val_type: return self.dict_to_text(value, indent) - else : + else: return self.list_to_text(value, indent) # dict杞崲涓簀son绫诲瀷 - def dict_to_json(self,value,indent): + def dict_to_json(self, value, indent): dict_ctx_list = [] - #if indent % 2 != 0 : + # if indent % 2 != 0 : # indent += 1 cur_indent = self.indent_ctx(indent) next_indent = self.indent_ctx(indent + 1) dict_len = len(value) tem_count = 0 - for k in ( value ) : + for k in (value): lvalue = value[k] lvalue_type = type(lvalue) - if tuple != lvalue_type and dict != lvalue_type and list != lvalue_type : + if tuple != lvalue_type and dict != lvalue_type and list != lvalue_type: tem_count += 1 - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) - if lk.replace(".", "").isdigit() : - key = "".join( ["\"",lk,"\"", ':'] ) - else : + if lk.replace(".", "").isdigit(): + key = "".join(["\"", lk, "\"", ':']) + else: key = lk.replace("\'", "\"") + ':' - if tem_count != dict_len : - val = "".join( [ next_indent, key + lv + ',\n' ] ) - else : - val = "".join( [ next_indent, key + lv ]) - dict_ctx_list.append( val ) + if tem_count != dict_len: + val = "".join([next_indent, key + lv + ',\n']) + else: + val = "".join([next_indent, key + lv]) + dict_ctx_list.append(val) - for k in ( value ) : + for k in (value): lvalue = value[k] lvalue_type = type(lvalue) - if tuple == lvalue_type or dict == lvalue_type or list == lvalue_type : + if tuple == lvalue_type or dict == lvalue_type or list == lvalue_type: tem_count += 1 - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) - if lk.replace(".", "").isdigit() : - key = "".join( ["\"",lk,"\"", ':'] ) - else : + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) + if lk.replace(".", "").isdigit(): + key = "".join(["\"", lk, "\"", ':']) + else: key = lk.replace("\'", "\"") + ':' - - if tem_count != dict_len : - val = "".join( [ next_indent, key + lv + ',\n' ] ) - else : - val = "".join( [ next_indent, key + lv ]) - dict_ctx_list.append( val ) + if tem_count != dict_len: + val = "".join([next_indent, key + lv + ',\n']) + else: + val = "".join([next_indent, key + lv]) + dict_ctx_list.append(val) dict_str = "".join(dict_ctx_list) - return True,"".join(["{\n" , dict_str, "\n",cur_indent,"}"] ) + return True, "".join(["{\n", dict_str, "\n", cur_indent, "}"]) # list杞崲涓簀son绫诲瀷 - def list_to_json(self,value,indent): + def list_to_json(self, value, indent): list_ctx_list = [] - #if indent % 2 != 0 : + # if indent % 2 != 0 : # indent += 1 cur_indent = self.indent_ctx(indent) next_indent = self.indent_ctx(indent + 1) @@ -155,47 +153,45 @@ class JsonobjectWriter(Writer): index_cnt = 1 list_len = len(value) tem_count = 0 - for v in value : + for v in value: tem_count += 1 - is_indent,lv = self.to_target_lang( v,indent + 1 ) - if tem_count != list_len : - val = "".join( [ next_indent, lv + ',\n' ] ) - else : - val = "".join( [ next_indent, lv]) - list_ctx_list.append( val ) + is_indent, lv = self.to_target_lang(v, indent + 1) + if tem_count != list_len: + val = "".join([next_indent, lv + ',\n']) + else: + val = "".join([next_indent, lv]) + list_ctx_list.append(val) index_cnt += 1 list_str = "".join(list_ctx_list) - return True,"".join(["[\n" , list_str, "\n",cur_indent,"]"] ) + return True, "".join(["[\n", list_str, "\n", cur_indent, "]"]) # 鍙橀噺杞崲鍒扮洰鏍囪瑷鐨勫瓧绗︿覆 - def to_target_lang(self,value,indent): - val_type = type( value ) - if int == val_type : - return False,str( value ) - elif long == val_type : - return False,str( value ) - elif float == val_type : + def to_target_lang(self, value, indent): + val_type = type(value) + if int == val_type: + return False, str(value) + elif long == val_type: + return False, str(value) + elif float == val_type: # 1001.0 -->> 001 鍘婚櫎澶氫綑灏忔暟鐐 - if int( value ) == value : - return False,str( int(value) ) - return False, str( value ) + if int(value) == value: + return False, str(int(value)) + return False, str(value) elif str == val_type or unicode == val_type: # 瀛楃涓茶鐢ㄥ崟寮曞彿锛屽洜涓篖ua閲屽崟寮曞彿绾у埆姣斿弻寮曞彿楂 - return False,"".join(["\"",value,"\""]) - elif tuple == val_type : + return False, "".join(["\"", value, "\""]) + elif tuple == val_type: value1 = list(value) - return self.list_to_json(value1,indent) - elif dict == val_type : - return self.dict_to_json(value,indent) - elif list == val_type : - return self.list_to_json(value,indent) - else : - raise Exception( "invalid type",val_type ) - - #鏂囦欢鍐呭 - def context(self,ctx): - is_indent,str_ctx = self.to_text( ctx, 0 ) - return "".join( [self.comment(), str_ctx] ) - - + return self.list_to_json(value1, indent) + elif dict == val_type: + return self.dict_to_json(value, indent) + elif list == val_type: + return self.list_to_json(value, indent) + else: + raise Exception("invalid type", val_type) + + # 鏂囦欢鍐呭 + def context(self, ctx): + is_indent, str_ctx = self.to_text(ctx, 0) + return "".join([self.comment(), str_ctx]) diff --git a/src/writer_lua.py b/src/writer_lua.py index bc76a06..3eb7a9f 100644 --- a/src/writer_lua.py +++ b/src/writer_lua.py @@ -1,8 +1,6 @@ #! python # -*- coding:utf-8 -*- -import os -import sys from writer import * try: @@ -26,6 +24,7 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class LuaWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): @@ -38,19 +37,19 @@ class LuaWriter(Writer): '\n-- excel sheet name: ' + self.sheet_name, '\nlocal ' + self.base_name + ' =\n' ] - return "\n".join( comment ) + return "\n".join(comment) # 鑾峰彇缂╄繘瀛楃涓 - def indent_ctx( self,indent ): + def indent_ctx(self, indent): if indent <= 0: return "" if indent not in INDENT_LIST: - ctx = BASE_INDENT*indent + ctx = BASE_INDENT * indent INDENT_LIST[indent] = ctx return INDENT_LIST[indent] - def dict_to_text(self, value, indent) : + def dict_to_text(self, value, indent): dict_ctx_list = [] cur_indent = self.indent_ctx(indent) @@ -58,45 +57,45 @@ class LuaWriter(Writer): tem_count = 0 total_len = len(value) - for k in ( value ) : + for k in (value): tem_count += 1 - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) comment = self.comment_text[k] val = '-- ' + comment + '\n' dict_ctx_list.append(val) - val_type = type( lk ) - if str == val_type : - if lk.replace(".", "").isdigit() : - key = "".join( ["[",lk,"]"] ) - else : + val_type = type(lk) + if str == val_type: + if lk.replace(".", "").isdigit(): + key = "".join(["[", lk, "]"]) + else: key = lk.replace("\'", "") - if tem_count != total_len : - val = "".join( [cur_indent, key," =", lv, ",\n\n", cur_indent] ) - else : - val = "".join( [cur_indent, key," = ",lv] ) + if tem_count != total_len: + val = "".join([cur_indent, key, " =", lv, ",\n\n", cur_indent]) + else: + val = "".join([cur_indent, key, " = ", lv]) - dict_ctx_list.append( val ) - dict_str = "".join( dict_ctx_list ) + dict_ctx_list.append(val) + dict_str = "".join(dict_ctx_list) - return False,"".join( ["{\n", cur_indent, dict_str, "\n}"] ) + return False, "".join(["{\n", cur_indent, dict_str, "\n}"]) - def list_to_dit(self, cur_key_index, total_key_cnt, onedict, storge_dict) : - for k in ( onedict ) : + def list_to_dit(self, cur_key_index, total_key_cnt, onedict, storge_dict): + for k in (onedict): key_index = self.keys_list.get(k, None) - if None != key_index and key_index == cur_key_index : + if None != key_index and key_index == cur_key_index: lv = onedict[k] - if cur_key_index == total_key_cnt : + if cur_key_index == total_key_cnt: storge_dict[lv] = onedict - else : - if None != storge_dict.get(lv, None) : + else: + if None != storge_dict.get(lv, None): olddict = storge_dict[lv] new_storge_dict = olddict self.list_to_dit(cur_key_index + 1, total_key_cnt, onedict, new_storge_dict) - else : - storge_dict[lv] ={} + else: + storge_dict[lv] = {} new_storge_dict = storge_dict[lv] self.list_to_dit(cur_key_index + 1, total_key_cnt, onedict, new_storge_dict) @@ -105,96 +104,96 @@ class LuaWriter(Writer): # 鍏堟妸鍚勪釜瀛楁鐨勬敞閲婃斁鍦ㄥ墠闈 comment_text_list = [] - for k in self.comment_text : + for k in self.comment_text: comment = self.comment_text[k] - k_indent,lk = self.to_target_lang( k,indent ) + k_indent, lk = self.to_target_lang(k, indent) lk = lk.replace("\'", "") - if None == comment : + if None == comment: comment = "" - val = "".join( [ '--: ', lk.ljust(20, " "), "\t## ", comment, "\n"] ) + val = "".join(['--: ', lk.ljust(20, " "), "\t## ", comment, "\n"]) - comment_text_list.append( val ) + comment_text_list.append(val) - comment_str = "".join( comment_text_list ) + comment_str = "".join(comment_text_list) list_text_list.append(comment_str) ## 澶勭悊澶氫釜key鐨勬儏鍐 key_value_list = {} key_cnt = len(self.keys_list) - for i, onedict in enumerate( value ) : + for i, onedict in enumerate(value): self.list_to_dit(1, key_cnt, onedict, key_value_list) - is_indent,lv = self.to_target_lang( key_value_list, 0 ) - list_str = "".join( lv ) + is_indent, lv = self.to_target_lang(key_value_list, 0) + list_str = "".join(lv) list_text_list.append(list_str) - return False,"".join( list_text_list ) + return False, "".join(list_text_list) # 杞崲涓烘枃鏈暟鎹 涔嬪墠瑙f瀽鍑烘潵鐨別xcel鏁版嵁瀛樻斁鏂瑰紡瀛樺湪LIST(array鏍煎紡)鍜孌ICT(object鏍煎紡)涓ょ绫诲瀷 - def to_text(self,value,indent): - val_type = type( value ) - if dict == val_type : + def to_text(self, value, indent): + val_type = type(value) + if dict == val_type: return self.dict_to_text(value, indent) - else : + else: return self.list_to_text(value, indent) # dict杞崲涓簂ua绫诲瀷 - def dict_to_lua(self,value,indent): + def dict_to_lua(self, value, indent): dict_ctx_list = [] - if indent % 2 != 0 : + if indent % 2 != 0: indent += 1 cur_indent = self.indent_ctx(indent) next_indent = self.indent_ctx(indent + 1) dict_len = len(value) tem_count = 0 - for k in ( value ) : + for k in (value): lvalue = value[k] lvalue_type = type(lvalue) - if tuple != lvalue_type and dict != lvalue_type and list != lvalue_type : + if tuple != lvalue_type and dict != lvalue_type and list != lvalue_type: tem_count += 1 - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) - if lk.replace(".", "").isdigit() : - key = "".join( ["[",lk,"]"] ) - else : + if lk.replace(".", "").isdigit(): + key = "".join(["[", lk, "]"]) + else: key = lk.replace("\'", "") - if tem_count != dict_len : - val = "".join( [ next_indent, key + " = " + lv + ',\n' ] ) - else : - val = "".join( [ next_indent, key + " = " + lv ]) - dict_ctx_list.append( val ) + if tem_count != dict_len: + val = "".join([next_indent, key + " = " + lv + ',\n']) + else: + val = "".join([next_indent, key + " = " + lv]) + dict_ctx_list.append(val) - for k in ( value ) : + for k in (value): lvalue = value[k] lvalue_type = type(lvalue) - if tuple == lvalue_type or dict == lvalue_type or list == lvalue_type : + if tuple == lvalue_type or dict == lvalue_type or list == lvalue_type: tem_count += 1 - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) - if lk.replace(".", "").isdigit() : - key = "".join( ["[",lk,"]"] ) - else : + if lk.replace(".", "").isdigit(): + key = "".join(["[", lk, "]"]) + else: key = lk.replace("\'", "") - if tem_count != dict_len : - val = "".join( [ next_indent, key + " = " + lv + ',\n' ] ) - else : - val = "".join( [ next_indent, key + " = " + lv ]) - dict_ctx_list.append( val ) + if tem_count != dict_len: + val = "".join([next_indent, key + " = " + lv + ',\n']) + else: + val = "".join([next_indent, key + " = " + lv]) + dict_ctx_list.append(val) dict_str = "".join(dict_ctx_list) - return True,"".join(['\n', cur_indent,"{\n" , dict_str, "\n",cur_indent,"}"] ) + return True, "".join(['\n', cur_indent, "{\n", dict_str, "\n", cur_indent, "}"]) # list杞崲涓簂ua绫诲瀷 - def list_to_lua(self,value,indent): + def list_to_lua(self, value, indent): list_ctx_list = [] - if indent % 2 != 0 : + if indent % 2 != 0: indent += 1 cur_indent = self.indent_ctx(indent) next_indent = self.indent_ctx(indent + 1) @@ -202,24 +201,24 @@ class LuaWriter(Writer): index_cnt = 1 list_len = len(value) tem_count = 0 - for v in value : + for v in value: tem_count += 1 - is_indent,lv = self.to_target_lang( v,indent + 1 ) - if tem_count != list_len : - val = "".join( [ next_indent, "[" + str(index_cnt) + "] = " + lv + ',\n' ] ) - else : - val = "".join( [ next_indent, "[" + str(index_cnt) + "] = " + lv ]) - list_ctx_list.append( val ) + is_indent, lv = self.to_target_lang(v, indent + 1) + if tem_count != list_len: + val = "".join([next_indent, "[" + str(index_cnt) + "] = " + lv + ',\n']) + else: + val = "".join([next_indent, "[" + str(index_cnt) + "] = " + lv]) + list_ctx_list.append(val) index_cnt += 1 list_str = "".join(list_ctx_list) - return True,"".join(['\n', cur_indent,"{\n" , list_str, "\n",cur_indent,"}"] ) + return True, "".join(['\n', cur_indent, "{\n", list_str, "\n", cur_indent, "}"]) - # tuple杞崲涓簂ua绫诲瀷 - def tuple_to_lua(self,value1,indent): + # tuple杞崲涓簂ua绫诲瀷 + def tuple_to_lua(self, value1, indent): value = list(value1) list_ctx_list = [] - if indent % 2 != 0 : + if indent % 2 != 0: indent += 1 cur_indent = self.indent_ctx(indent) next_indent = self.indent_ctx(indent + 1) @@ -227,47 +226,44 @@ class LuaWriter(Writer): index_cnt = 1 list_len = len(value) tem_count = 0 - for v in value : + for v in value: tem_count += 1 - is_indent,lv = self.to_target_lang( v,indent + 1 ) - if tem_count != list_len : - val = "".join( [ next_indent, "[" + str(index_cnt) + "] = " + lv + ',\n' ] ) - else : - val = "".join( [ next_indent, "[" + str(index_cnt) + "] = " + lv ]) - list_ctx_list.append( val ) + is_indent, lv = self.to_target_lang(v, indent + 1) + if tem_count != list_len: + val = "".join([next_indent, "[" + str(index_cnt) + "] = " + lv + ',\n']) + else: + val = "".join([next_indent, "[" + str(index_cnt) + "] = " + lv]) + list_ctx_list.append(val) index_cnt += 1 list_str = "".join(list_ctx_list) - return True,"".join(['\n', cur_indent,"{\n" , list_str, "\n",cur_indent,"}"] ) - + return True, "".join(['\n', cur_indent, "{\n", list_str, "\n", cur_indent, "}"]) # 鍙橀噺杞崲鍒扮洰鏍囪瑷鐨勫瓧绗︿覆 - def to_target_lang(self,value,indent): - val_type = type( value ) - if int == val_type : - return False,str( value ) - elif long == val_type : - return False,str( value ) - elif float == val_type : + def to_target_lang(self, value, indent): + val_type = type(value) + if int == val_type: + return False, str(value) + elif long == val_type: + return False, str(value) + elif float == val_type: # 1001.0 -->> 001 鍘婚櫎澶氫綑灏忔暟鐐 - if int( value ) == value : - return False,str( int(value) ) - return False,str( value ) + if int(value) == value: + return False, str(int(value)) + return False, str(value) elif str == val_type or unicode == val_type: # 瀛楃涓茶鐢ㄥ崟寮曞彿锛屽洜涓篖ua閲屽崟寮曞彿绾у埆姣斿弻寮曞彿楂 - return False,"".join(["'",value,"'"]) - elif tuple == val_type : - return self.tuple_to_lua(value,indent) - elif dict == val_type : - return self.dict_to_lua(value,indent) - elif list == val_type : - return self.list_to_lua(value,indent) - else : - raise Exception( "invalid type",val_type ) - - #鏂囦欢鍐呭 - def context(self,ctx): - is_indent,str_ctx = self.to_text( ctx,1 ) - return "".join( [self.comment(), str_ctx, "\nreturn ", self.base_name] ) - - + return False, "".join(["'", value, "'"]) + elif tuple == val_type: + return self.tuple_to_lua(value, indent) + elif dict == val_type: + return self.dict_to_lua(value, indent) + elif list == val_type: + return self.list_to_lua(value, indent) + else: + raise Exception("invalid type", val_type) + + # 鏂囦欢鍐呭 + def context(self, ctx): + is_indent, str_ctx = self.to_text(ctx, 1) + return "".join([self.comment(), str_ctx, "\nreturn ", self.base_name]) diff --git a/src/writer_python.py b/src/writer_python.py index 59838d6..43f56e2 100644 --- a/src/writer_python.py +++ b/src/writer_python.py @@ -1,8 +1,6 @@ #! python # -*- coding:utf-8 -*- -import os -import sys from writer import * try: @@ -26,12 +24,14 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class PythonWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): return ".py" # 鏂囦欢娉ㄩ噴(鍗冧竾涓嶈鍔犳椂闂达紝褰卞搷svn) + def comment(self): comment = [ '## Automatic generation from -->>' @@ -40,41 +40,40 @@ class PythonWriter(Writer): '\ndefmodule ' + self.base_name.title() + ' do\n\n' ] - return "\n".join( comment ) + return "\n".join(comment) # 鑾峰彇缂╄繘瀛楃涓 - def indent_ctx( self,indent ): + def indent_ctx(self, indent): if indent <= 0: return "" if indent not in INDENT_LIST: INDENT_LIST[indent] = "" else: - ctx = BASE_INDENT*indent + ctx = BASE_INDENT * indent INDENT_LIST[indent] = ctx return INDENT_LIST[indent] - def dict_to_text(self, value, indent) : - + def dict_to_text(self, value, indent): dict_text_list = [] - for k in ( value ) : - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + for k in (value): + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) comment = self.comment_text[k] - val_type = type( lk ) - if str == val_type : + val_type = type(lk) + if str == val_type: lk = ':' + lk.replace("\"", "") - key = "".join( [" def get(",lk,") do\n"] ) + key = "".join([" def get(", lk, ") do\n"]) - val = "".join( [" ## ", comment, "\n", key, " ", lv, "\n end\n\n"] ) + val = "".join([" ## ", comment, "\n", key, " ", lv, "\n end\n\n"]) - dict_text_list.append( val ) + dict_text_list.append(val) - dict_str = "".join( dict_text_list ) + dict_str = "".join(dict_text_list) dict_str = dict_str + " def get(_) do\n :undefined\n end\n\nend" return False, dict_str @@ -84,70 +83,70 @@ class PythonWriter(Writer): struct_text_list = [] struct_len = len(self.comment_text) tem_count = 0 - for k in self.comment_text : + for k in self.comment_text: tem_count += 1 comment = self.comment_text[k] - k_indent,lk = self.to_target_lang( k,indent ) - val_type = type( lk ) - if str == val_type : - if tem_count != struct_len : + k_indent, lk = self.to_target_lang(k, indent) + val_type = type(lk) + if str == val_type: + if tem_count != struct_len: lk = ':' + lk.replace("\"", "") + ',' - else : + else: lk = ':' + lk.replace("\"", "") - if None == comment : + if None == comment: comment = "" - val = "".join( [lk.ljust(20, " "), "\t## ", comment, "\n"] ) + val = "".join([lk.ljust(20, " "), "\t## ", comment, "\n"]) - struct_text_list.append( val ) + struct_text_list.append(val) - struct_str = " ".join( struct_text_list ) + struct_str = " ".join(struct_text_list) end_str = " defstruct [\n " + struct_str + " ]\n\n" list_text_list.append(end_str) all_key_list = [] # 鐢熸垚 get() 鍑芥暟 - for i, onedict in enumerate( value ) : + for i, onedict in enumerate(value): # 鐢熸垚瀵瑰簲鐨 key key_list = [] - for k in ( onedict ) : - if None != self.keys_list.get(k, None) : - is_indent,lv = self.to_target_lang( onedict[k],indent + 1 ) + for k in (onedict): + if None != self.keys_list.get(k, None): + is_indent, lv = self.to_target_lang(onedict[k], indent + 1) key_list.append(lv) all_key_list.append(key_list) - tem = ", ".join( key_list ) + tem = ", ".join(key_list) - key = "".join( [" def get(",tem,") do\n %", self.base_name.title(), "{\n "] ) + key = "".join([" def get(", tem, ") do\n %", self.base_name.title(), "{\n "]) # 鐢熸垚瀵瑰簲鐨剉alue value_list = [] onedict_len = len(onedict) tem_count = 0 - for k in ( onedict ) : + for k in (onedict): tem_count += 1 - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( onedict[k],indent + 1 ) + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(onedict[k], indent + 1) - val_type = type( lk ) - if str == val_type : + val_type = type(lk) + if str == val_type: lk = ':' + lk.replace("\"", "") - if tem_count != onedict_len : - oneval = "".join( [lk, " => ", lv , ",\n"] ) - value_list.append( oneval ) - else : - oneval = "".join( [lk, " => ", lv , "\n"] ) - value_list.append( oneval ) + if tem_count != onedict_len: + oneval = "".join([lk, " => ", lv, ",\n"]) + value_list.append(oneval) + else: + oneval = "".join([lk, " => ", lv, "\n"]) + value_list.append(oneval) value_list_str = " ".join(value_list) - end_str = "".join( [key, value_list_str, " }\n end\n\n"] ) + end_str = "".join([key, value_list_str, " }\n end\n\n"]) - list_text_list.append( end_str ) + list_text_list.append(end_str) underline_list = [] - for i in self.keys_list : + for i in self.keys_list: underline_list.append('_') end_str = ", ".join(underline_list) @@ -159,149 +158,147 @@ class PythonWriter(Writer): get_all_fun = [] allkey_len = len(all_key_list) tem_count = 0 - for i, ival in enumerate(all_key_list) : + for i, ival in enumerate(all_key_list): tem_count += 1 - if tem_count != allkey_len : + if tem_count != allkey_len: oneval = '{' + ", ".join(ival) + '},\n' get_all_fun.append(oneval) - else : + else: oneval = '{' + ", ".join(ival) + '}\n' get_all_fun.append(oneval) value_list_str = " ".join(get_all_fun) start_str = ' def get_all() do\n [\n ' - end_str = "".join( [start_str, value_list_str, " ]\n end\n\n"] ) + end_str = "".join([start_str, value_list_str, " ]\n end\n\n"]) - list_text_list.append( end_str ) + list_text_list.append(end_str) # 鐢熸垚 get_list() 鍑芥暟 get_list_fun = [] keys_len = len(self.keys_list) - for key in self.keys_list : + for key in self.keys_list: keyindex = self.keys_list[key] - if keyindex == 1 : - list_text_list.append( ' def get_list() do\n get_all()\n end\n\n') - elif keyindex <= keys_len : + if keyindex == 1: + list_text_list.append(' def get_list() do\n get_all()\n end\n\n') + elif keyindex <= keys_len: get_tem_dict = {} underline_list = [] - for i, ival in enumerate(all_key_list) : + for i, ival in enumerate(all_key_list): key_tem_list = [] j = 0 underline_list = [] - while j < keyindex - 1 : + while j < keyindex - 1: key_tem_list.append(ival[j]) underline_list.append('_') j += 1 keystr = '(' + ", ".join(key_tem_list) + ')' - if None != get_tem_dict.get(keystr, None) : + if None != get_tem_dict.get(keystr, None): oldlist = get_tem_dict[keystr] oldlist.append(ival) get_tem_dict[keystr] = oldlist - else : + else: get_tem_dict[keystr] = [ival] - for onekey in get_tem_dict : + for onekey in get_tem_dict: value_tem_list = [] valuelist = get_tem_dict[onekey] value_len = len(valuelist) tem_count = 0 - for l, lval in enumerate(valuelist) : + for l, lval in enumerate(valuelist): tem_count += 1 - if tem_count != value_len : + if tem_count != value_len: oneval = '{' + ", ".join(lval) + '},\n' value_tem_list.append(oneval) - else : + else: oneval = '{' + ", ".join(lval) + '}\n' value_tem_list.append(oneval) start_str = ' def get_list' + onekey + ' do\n [\n ' - end_str = "".join( [start_str, " ".join(value_tem_list), " ]\n end\n\n"] ) + end_str = "".join([start_str, " ".join(value_tem_list), " ]\n end\n\n"]) get_list_fun.append(end_str) - no_match_str = "".join(' def get_list(' + ", ".join(underline_list) + ') do\n []\n end\n\n') + no_match_str = "".join( + ' def get_list(' + ", ".join(underline_list) + ') do\n []\n end\n\n') get_list_fun.append(no_match_str) - value_list_str = "".join(get_list_fun) + 'end' - list_text_list.append( value_list_str ) - dict_str = "".join( list_text_list ) + list_text_list.append(value_list_str) + dict_str = "".join(list_text_list) return False, dict_str # 杞崲涓篹rlang 鏂囨湰鏁版嵁 涔嬪墠瑙f瀽鍑烘潵鐨別xcel鏁版嵁瀛樻斁鏂瑰紡瀛樺湪LIST(array鏍煎紡)鍜孌ICT(object鏍煎紡)涓ょ绫诲瀷 - def to_text(self,value,indent): - val_type = type( value ) - if dict == val_type : + def to_text(self, value, indent): + val_type = type(value) + if dict == val_type: return self.dict_to_text(value, indent) - else : + else: return self.list_to_text(value, indent) # python鐨刣ict杞崲涓篹lixir鐨刴ap绫诲瀷 - def dict_to_elixir(self,value,indent): + def dict_to_elixir(self, value, indent): dict_ctx_list = [] - for k in ( value ) : - k_indent,lk = self.to_target_lang( k,indent ) - is_indent,lv = self.to_target_lang( value[k],indent + 1 ) + for k in (value): + k_indent, lk = self.to_target_lang(k, indent) + is_indent, lv = self.to_target_lang(value[k], indent + 1) - val_type = type( lk ) - if str == val_type : + val_type = type(lk) + if str == val_type: lk = lk.replace("\"", "\'") - key = "".join( [lk," => "] ) - val = "".join( [key, lv] ) + key = "".join([lk, " => "]) + val = "".join([key, lv]) dict_ctx_list.append(val) - dict_str = ", ".join( dict_ctx_list ) - return False,"".join( ["%{",dict_str,"}"] ) + dict_str = ", ".join(dict_ctx_list) + return False, "".join(["%{", dict_str, "}"]) # python鐨刲ist杞崲涓篹lixir鐨刲ist绫诲瀷 - def list_to_elixir(self,value,indent): + def list_to_elixir(self, value, indent): list_ctx_list = [] - for v in value : - is_indent,lv = self.to_target_lang( v,indent + 1 ) - list_ctx_list.append( lv ) - + for v in value: + is_indent, lv = self.to_target_lang(v, indent + 1) + list_ctx_list.append(lv) - list_str = ", ".join( list_ctx_list ) - return False,"".join( ["[",list_str,"]"] ) + list_str = ", ".join(list_ctx_list) + return False, "".join(["[", list_str, "]"]) # python鐨則uple杞崲涓篹lixir鐨則uple绫诲瀷 - def tuple_to_elixir(self,value,indent): + def tuple_to_elixir(self, value, indent): tuple_ctx_list = [] - for v in value : - is_indent,lv = self.to_target_lang( v,indent + 1 ) - tuple_ctx_list.append( lv ) + for v in value: + is_indent, lv = self.to_target_lang(v, indent + 1) + tuple_ctx_list.append(lv) # 杩斿洖 {a,b,c}杩欑涓嶆崲琛岀殑鏍煎紡 - list_str = ", ".join( tuple_ctx_list ) - return False,"".join( ["{",list_str,"}"] ) - + list_str = ", ".join(tuple_ctx_list) + return False, "".join(["{", list_str, "}"]) # 鍙橀噺杞崲鍒扮洰鏍囪瑷瀛楃涓 - def to_target_lang(self,value,indent): - val_type = type( value ) - if int == val_type : - return False,str( value ) - elif long == val_type : - return False,str( value ) - elif float == val_type : + def to_target_lang(self, value, indent): + val_type = type(value) + if int == val_type: + return False, str(value) + elif long == val_type: + return False, str(value) + elif float == val_type: # 1001.0 -->> 001 鍘婚櫎澶氫綑灏忔暟鐐 - if int( value ) == value : - return False,str( int(value) ) - return False,str( value ) + if int(value) == value: + return False, str(int(value)) + return False, str(value) elif str == val_type or unicode == val_type: - return False, "".join(["\"",value,"\""]) - elif tuple == val_type : - return self.tuple_to_elixir(value,indent) - elif dict == val_type : - return self.dict_to_elixir(value,indent) - elif list == val_type : - return self.list_to_elixir(value,indent) - else : - raise Exception( "invalid type",val_type ) - - #鏂囦欢鍐呭 - def context(self,ctx): - is_indent,str_ctx = self.to_text( ctx,0 ) - return "".join( [self.comment(),"",str_ctx] ) + return False, "".join(["\"", value, "\""]) + elif tuple == val_type: + return self.tuple_to_elixir(value, indent) + elif dict == val_type: + return self.dict_to_elixir(value, indent) + elif list == val_type: + return self.list_to_elixir(value, indent) + else: + raise Exception("invalid type", val_type) + + # 鏂囦欢鍐呭 + def context(self, ctx): + is_indent, str_ctx = self.to_text(ctx, 0) + return "".join([self.comment(), "", str_ctx]) diff --git a/src/writer_xml.py b/src/writer_xml.py index 708ef73..d6ce6f6 100644 --- a/src/writer_xml.py +++ b/src/writer_xml.py @@ -1,9 +1,8 @@ #! python # -*- coding:utf-8 -*- -import os -import sys from xml.dom.minidom import Document + from writer import * try: @@ -27,107 +26,109 @@ BASE_LENGTH = 60 BASE_INDENT = " " INDENT_LIST = {} + class JsonWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): return ".json" # 鏂囦欢鍐呭(瀛楃涓) - def context(self,ctx): - return json.dumps(ctx,ensure_ascii=False,\ - indent=4,sort_keys=True,separators=(',', ':') ) + def context(self, ctx): + return json.dumps(ctx, ensure_ascii=False, \ + indent=4, sort_keys=True, separators=(',', ':')) class XmlWriter(Writer): # 鏂囦欢鍚庣紑 def suffix(self): return ".xml" + # 娉ㄩ噴寮濮 def comment_start(self): return "" - #鍒涘缓鏍瑰厓绱 + # 鍒涘缓鏍瑰厓绱 def root_element(self): - root = self.doc.createElement( self.base_name ) + root = self.doc.createElement(self.base_name) return root # dict绫诲瀷杞崲涓簒ml - def dict_to_xml(self,root,value): + def dict_to_xml(self, root, value): # 闇瑕佸key鎺掑簭锛屼笉鐒舵瘡娆″鍑虹殑xml瀛楁鏄贡鐨勶紝瀵圭増鏈鐞嗕笉鍙嬪ソ - for k in sorted( value ) : + for k in sorted(value): v = value[k] - sub_root = self.doc.createElement( k ) + sub_root = self.doc.createElement(k) - self.to_xml( sub_root,v ) - root.appendChild( sub_root ) + self.to_xml(sub_root, v) + root.appendChild(sub_root) # list绫诲瀷杞崲涓簒ml - def list_to_xml(self,root,value): - for k,v in enumerate( value ) : + def list_to_xml(self, root, value): + for k, v in enumerate(value): # xml涓苟涓嶆敮鎸乤rray锛岀敤item鏉ュ懡鍚嶏紝澶栧姞涓涓猧ndex灞炴 - sub_root = self.doc.createElement( "item" ) - sub_root.setAttribute( "index",str( k ) ) + sub_root = self.doc.createElement("item") + sub_root.setAttribute("index", str(k)) + + self.to_xml(sub_root, v) + root.appendChild(sub_root) - self.to_xml( sub_root,v ) - root.appendChild( sub_root ) # tuple绫诲瀷杞崲涓簒ml - def tuple_to_xml(self,root,value): + def tuple_to_xml(self, root, value): valueList = list(value) - for k,v in enumerate( valueList ) : + for k, v in enumerate(valueList): # xml涓苟涓嶆敮鎸乤rray锛岀敤item鏉ュ懡鍚嶏紝澶栧姞涓涓猧ndex灞炴 - sub_root = self.doc.createElement( "item" ) - sub_root.setAttribute( "index",str( k ) ) + sub_root = self.doc.createElement("item") + sub_root.setAttribute("index", str(k)) - self.to_xml( sub_root,v ) - root.appendChild( sub_root ) + self.to_xml(sub_root, v) + root.appendChild(sub_root) # 杞崲涓簒ml鑺傜偣 - def to_xml(self,root,value): + def to_xml(self, root, value): sub_node = None val_type_str = None - val_type = type( value ) - if int == val_type : + val_type = type(value) + if int == val_type: # python3涓病鏈塋ong绫诲瀷锛宨nt64涔熺敤int琛ㄧず val_type_str = "int64" - sub_node = self.doc.createTextNode( str( value ) ) - elif long == val_type : + sub_node = self.doc.createTextNode(str(value)) + elif long == val_type: val_type_str = "int64" - sub_node = self.doc.createTextNode( str( value ) ) - elif float == val_type : + sub_node = self.doc.createTextNode(str(value)) + elif float == val_type: val_type_str = "number" # 鍘婚櫎甯﹀皬鏁版椂鐨勫皬鏁扮偣锛100.0 ==>> 100 - if long( value ) == float( value ) : - sub_node = self.doc.createTextNode( str( long( value ) ) ) + if long(value) == float(value): + sub_node = self.doc.createTextNode(str(long(value))) else: - sub_node = self.doc.createTextNode( str( value ) ) - elif str == val_type or unicode == val_type : + sub_node = self.doc.createTextNode(str(value)) + elif str == val_type or unicode == val_type: val_type_str = "string" - sub_node = self.doc.createTextNode( value ) - elif tuple == val_type : - self.tuple_to_xml( root,value ) - elif dict == val_type : - self.dict_to_xml( root,value ) - elif list == val_type : - self.list_to_xml( root,value ) - else : - raise Exception( "invalid type",val_type ) + sub_node = self.doc.createTextNode(value) + elif tuple == val_type: + self.tuple_to_xml(root, value) + elif dict == val_type: + self.dict_to_xml(root, value) + elif list == val_type: + self.list_to_xml(root, value) + else: + raise Exception("invalid type", val_type) # 绫诲瀷涓篸ict鎴栬卨ist鐨勶紝娌℃湁杩欎釜type灞炴 - if val_type_str : root.setAttribute( "type",val_type_str ) - if sub_node : root.appendChild( sub_node ) + if val_type_str: root.setAttribute("type", val_type_str) + if sub_node: root.appendChild(sub_node) # 鏂囦欢鍐呭 - def context(self,ctx): - #鍒涘缓DOM鏂囨。瀵硅薄 + def context(self, ctx): + # 鍒涘缓DOM鏂囨。瀵硅薄 self.doc = Document() root = self.root_element() - self.to_xml( root,ctx ) - self.doc.appendChild( root ) - - return self.comment() + self.doc.toprettyxml( indent=" " ) - + self.to_xml(root, ctx) + self.doc.appendChild(root) + return self.comment() + self.doc.toprettyxml(indent=" ")