Browse Source

push

master
AICells 6 years ago
parent
commit
3ac2b7fdd8
63 changed files with 7139 additions and 2 deletions
  1. +5
    -2
      .gitattributes
  2. +110
    -0
      .gitignore
  3. +3
    -0
      .gitmodules
  4. +112
    -0
      ConfigConvertTool.py
  5. +71
    -0
      README.md
  6. +289
    -0
      client/cfg_array_example1.xml
  7. +243
    -0
      client/cfg_array_example2.xml
  8. +4
    -0
      client/cfg_array_example3.xml
  9. +88
    -0
      client/cfg_object.xml
  10. +88
    -0
      client/cfg_object1_cfg_object.xml
  11. +219
    -0
      color_print.py
  12. BIN
      config_excel/A_array表示例--cfg_array.xlsx
  13. BIN
      config_excel/A_object表示例--cfg_object.xlsx
  14. +442
    -0
      decoder.py
  15. +12
    -0
      lancher.bat
  16. +6
    -0
      lancher.sh
  17. +14
    -0
      server/cfg_array.erl
  18. +16
    -0
      server/cfg_array.ex
  19. +3
    -0
      server/cfg_array.json
  20. +10
    -0
      server/cfg_array.lua
  21. +311
    -0
      server/cfg_array_example1.erl
  22. +360
    -0
      server/cfg_array_example1.ex
  23. +13
    -0
      server/cfg_array_example1.hrl
  24. +332
    -0
      server/cfg_array_example1.json
  25. +433
    -0
      server/cfg_array_example1.lua
  26. +74
    -0
      server/cfg_array_example2.erl
  27. +89
    -0
      server/cfg_array_example2.ex
  28. +12
    -0
      server/cfg_array_example2.hrl
  29. +217
    -0
      server/cfg_array_example2.json
  30. +282
    -0
      server/cfg_array_example2.lua
  31. +14
    -0
      server/cfg_array_example3.erl
  32. +16
    -0
      server/cfg_array_example3.ex
  33. +3
    -0
      server/cfg_array_example3.json
  34. +10
    -0
      server/cfg_array_example3.lua
  35. +58
    -0
      server/cfg_object.erl
  36. +71
    -0
      server/cfg_object.ex
  37. +102
    -0
      server/cfg_object.json
  38. +153
    -0
      server/cfg_object.lua
  39. +71
    -0
      server/cfg_object1_cfg_object.ex
  40. +4
    -0
      slpp/.gitignore
  41. +19
    -0
      slpp/LICENSE
  42. +41
    -0
      slpp/README.markdown
  43. +0
    -0
      slpp/__init__.py
  44. +13
    -0
      slpp/setup.py
  45. BIN
      slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229.zip
  46. +4
    -0
      slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/.gitignore
  47. +19
    -0
      slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/LICENSE
  48. +41
    -0
      slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/README.markdown
  49. +0
    -0
      slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/__init__.py
  50. +13
    -0
      slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/setup.py
  51. +262
    -0
      slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/slpp.py
  52. +182
    -0
      slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/tests.py
  53. +262
    -0
      slpp/slpp.py
  54. +182
    -0
      slpp/tests.py
  55. +56
    -0
      writer.py
  56. +319
    -0
      writer_elixir.py
  57. +259
    -0
      writer_erlang_erl.py
  58. +152
    -0
      writer_erlang_hrl.py
  59. +41
    -0
      writer_json_array.py
  60. +201
    -0
      writer_json_object.py
  61. +273
    -0
      writer_lua.py
  62. +307
    -0
      writer_python.py
  63. +133
    -0
      writer_xml.py

+ 5
- 2
.gitattributes View File

@ -1,2 +1,5 @@
# Auto detect text files and perform LF normalization
* text=auto
* text eol=lf
*.zip binary
*.tar.gz binary
*.tar.bz2 binary
*.xlsx binary

+ 110
- 0
.gitignore View File

@ -0,0 +1,110 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# yongzhong office temp file
$*
# xlsx temp file
~*.xlsx
.~*.xlsx
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# dotenv
.env
# virtualenv
.venv
venv/
ENV/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/

+ 3
- 0
.gitmodules View File

@ -0,0 +1,3 @@
[submodule "slpp"]
path = slpp
url = https://github.com/changnet/slpp.git

+ 112
- 0
ConfigConvertTool.py View File

@ -0,0 +1,112 @@
#! python
# -*- coding:utf-8 -*-
import os
import time
from writer import *
from writer_erlang_erl import *
from writer_erlang_hrl import *
from writer_elixir import *
from writer_lua import *
from writer_xml import *
from writer_json_object import *
from writer_json_array import *
from writer_python import *
from optparse import OptionParser
from decoder import ExcelDoc
class Reader:
# @input_path:excel文件所在目录
# @srv_path :server输出目录
# @clt_path :客户端输出目录
# @timeout :只处理文档最后更改时间在N秒内的文档
# @suffix :excel文件后缀
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_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" )
def attention(self):
print("*****************************开始导表*****************************\n")
def can_read(self,file,abspath):
if not os.path.isfile( abspath ): return False
# ~开头的excel文件是临时文件,linux下wps临时文件以.~开头
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 )
if now - mtime > self.timeout: return False
return True
def read(self):
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))
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 )
for file in file_list:
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 ) )
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__':
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" )
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.attention()
reader.read()

+ 71
- 0
README.md View File

@ -0,0 +1,71 @@
# py_exceltools
python3 基于openpyxl的excel转换工具。支持xlsx文件转换为erlang,elixir,lua,json,xml,python等配置文件。
关于openpyxl库:https://pypi.python.org/pypi/openpyxl。
## python和openpyxl安装
linux安装
apt-get install python-pip
pip install openpyxl
win安装
安装python(同时安装pip并添加到Path)
安装openpyxl, 在安装python后在cmd中运行: pip install openpyxl
# 使用
lancher.bat(win)和lancher.sh(linux)为对应运行脚本。
当前配置了用于参考的参数来转换example.xlsx,
可在对应server、client输出文件夹查看生成配置效果。
参数:
--input :需要转换的excel文件所在目录
--srv : 服务端配置文件输出目录
--clt : 客户端配置文件输出目录
--timeout : 需要转换的excel文件最后更新时间距当前时间秒数。-1转换所有
--suffix :excel文件后缀,通常为.xlsx
--swriter : 服务端配置文件转换器,可以指定为: erlanghrl,erlangerl,elixir,lua,jsonarray,jsonobject,xml,python
--cwriter : 客户端配置文件转换器,可以指定为: erlanghrl,erlangerl,elixir,lua,jsonarray,jsonobject,xml,python
注:对于client和server,如果未配置输出目录或转换器,则不会导出。
# 数据类型
支持int(int64), number(float), string, tuple, list, dict, json、lua
其中tuple, list, dict 为 python原生数据结构 json 为json数据类型 Lua为 lua table
# 数据格式示范(可以参考本工具自带的示例配置表)
int 整数 1,2,1000 64位
number 整数或者小数都OK
string 字符串 excel表中配置时不需要额外加双引号
tuple (元素, 元素, ...) 元素可以为 int number string tuple list dict
list [元素, 元素, ...] 元素可以为 int number string tuple list dict
dict [key:value, key:value, ...] key可以为 int number string tuple value可以为 int number string tuple list dict
特别注意该类型的使用 因为在一些语言中 对应dict类似的类型的key不支持 int 比如 jsonarray和xml,如果在转成jsonarray和xml时key不能配置为int和number
json {key:value, key:value, ...}该类型为json的对象类型 Key为字符串, Value可以为任意Json数据类型即可以是对象,数字,基本数据类型。
lua 该类型为lua的table类型
其中 list dict json 三种数据格式可以互相嵌套
转换时会将这些数据类型转换为其他语言支持的数据类型,另外注意点是一些其他语言的一些限制
比如 json不能用数字做为对象的Key(), xml的也不能用数字作为标签, 在配置的时候需要注意
而且导出xml和jsonjsonarray都是用的库,出错的时候不太好找到对应配置错误的数据,需要配置前
就额外注意,以免不必要的懵逼和浪费时间,策划不太明白的可以请教程序或者百度
# 打包exe
部署时,可以将python打包成exe。建议使用pyinstaller。
pyinstaller3.2.1尚不支持python3.6.1,建议使用python 3.5。
pip install pyinstaller
pyinstaller -F -c ConfigConvertTool.py
excel文件名命名格式
为了表名的可视化和可理解性,文件命名支持 MMM-NNN.xlsx的方式。MMM可以是任意字符(一般为文件中文名,但是不用下划线结尾),
作为文件名的注释性描述。NNN只能是数字,字母和下划线(不能以下划线开头和数字开头),作为导出的配置以NNN做为表名前缀
excel sheet命名格式
为了考虑策划会使用一个excel配置同一的功能的多个配置子表,且方便导出和查看,sheet命名为YYY-XXX或者 YYY+XXX,
或者YYY (里面不包含 "+"""-"), YYY可以为任意字符(一般为中文描述),XXX为导出配置的表名后缀,
当sheet命名为 YYY-XXX或者 YYY+XXX时 导出文件名为: NNN_XXX.lang(此种命名一般用于 一个excel配置多个需要导出的sheet页签)
当sheet命名为 YYY 时 导出文件名为: NNN.lang (此种命名用法仅仅用于一个excel只配置一个需要导出的sheet页签)
lang为目标语言的后缀名
具体示例
A_arrary表示例--cfg_array.xlsx 前缀Y可以用方便排序显示 更多具体参见配置excel示例
* 在string中无法直接使用换行等特殊称号。请用\n等转义字符替代。
* 由于xml并不存在数组等结构,不建议使用。
* 工具会检测server和client标识。如果不存在,则不导出些表。方便策划做备注

+ 289
- 0
client/cfg_array_example1.xml View File

@ -0,0 +1,289 @@
<?xml version="1.0" ?>
<cfg_array_example1>
<item index="0">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">900</item>
</item>
</attr>
<desc type="string">从小城镇</desc>
<id type="int64">1001</id>
<level type="int64">88</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos1</str>
<sub_level type="number">1</sub_level>
</item>
<item index="1">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">900</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1001</id>
<level type="int64">88</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos1</str>
<sub_level type="number">2</sub_level>
</item>
<item index="2">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">900</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1001</id>
<level type="int64">89</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos1</str>
<sub_level type="number">89</sub_level>
</item>
<item index="3">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">900</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1001</id>
<level type="int64">88</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos2</str>
<sub_level type="number">88.9</sub_level>
</item>
<item index="4">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">900</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1001</id>
<level type="int64">89</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos2</str>
<sub_level type="number">89</sub_level>
</item>
<item index="5">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">901</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1002</id>
<level type="int64">88</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos1</str>
<sub_level type="number">88</sub_level>
</item>
<item index="6">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">900</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1002</id>
<level type="int64">89</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos1</str>
<sub_level type="number">89</sub_level>
</item>
<item index="7">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">901</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1002</id>
<level type="int64">90</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos1</str>
<sub_level type="number">90</sub_level>
</item>
<item index="8">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">901</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1002</id>
<level type="int64">88</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos2</str>
<sub_level type="number">88</sub_level>
</item>
<item index="9">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">900</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1002</id>
<level type="int64">89</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos2</str>
<sub_level type="number">89</sub_level>
</item>
<item index="10">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">901</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1002</id>
<level type="int64">90</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos2</str>
<sub_level type="number">90</sub_level>
</item>
<item index="11">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">902</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1003</id>
<level type="int64">85</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos1</str>
<sub_level type="number">85</sub_level>
</item>
<item index="12">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">903</item>
</item>
</attr>
<desc type="string">有钱就可以买</desc>
<id type="int64">1004</id>
<level type="int64">80</level>
<name type="string">黑切+蓝盾</name>
<str type="string">pos1</str>
<sub_level type="number">80</sub_level>
</item>
</cfg_array_example1>

+ 243
- 0
client/cfg_array_example2.xml View File

@ -0,0 +1,243 @@
<?xml version="1.0" ?>
<cfg_array_example2>
<item index="0">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">900</item>
</item>
<item index="3">
<add>
<item index="0" type="int64">4</item>
<item index="1" type="int64">100</item>
</add>
</item>
</attr>
<award1>
<item index="0" type="int64">1</item>
<item index="1" type="int64">2</item>
<item index="2" type="int64">3</item>
</award1>
<award2>
<id type="int64">1</id>
<num type="int64">3</num>
<type type="int64">2</type>
</award2>
<desc>
<item index="0" type="string">来源1</item>
<item index="1" type="string">来源2</item>
<item index="2" type="string">来源4</item>
</desc>
<id type="number">1</id>
<material>
<item index="0">
<count type="int64">1</count>
<id type="int64">10001</id>
<res type="int64">1</res>
</item>
<item index="1">
<count type="int64">1</count>
<id type="int64">10001</id>
<res type="int64">1</res>
</item>
</material>
<name type="string">examp1001</name>
</item>
<item index="1">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">901</item>
</item>
<item index="3">
<add>
<item index="0" type="int64">5</item>
<item index="1" type="int64">100</item>
</add>
</item>
</attr>
<award1>
<item index="0" type="int64">1</item>
<item index="1" type="int64">2</item>
<item index="2" type="int64">3</item>
</award1>
<award2>
<id type="int64">1</id>
<num type="int64">3</num>
<type type="int64">2</type>
</award2>
<desc>
<item index="0" type="string">来源1</item>
<item index="1" type="string">来源2</item>
<item index="2" type="string">来源4</item>
</desc>
<id type="number">2</id>
<material>
<count type="int64">1</count>
<id type="int64">10001</id>
<res type="int64">1</res>
</material>
<name type="string">examp1002</name>
</item>
<item index="2">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">902</item>
</item>
<item index="3">
<add>
<item index="0" type="int64">6</item>
<item index="1" type="int64">100</item>
</add>
</item>
</attr>
<award1>
<item index="0" type="int64">1</item>
<item index="1" type="int64">2</item>
<item index="2" type="int64">3</item>
</award1>
<award2>
<id type="int64">1</id>
<num type="int64">3</num>
<type type="int64">2</type>
</award2>
<desc>
<item index="0" type="string">来源1</item>
<item index="1" type="string">来源2</item>
<item index="2" type="string">来源5</item>
</desc>
<id type="number">3</id>
<material>
<item index="0" type="int64">1</item>
<item index="1" type="int64">2</item>
<item index="2" type="int64">3</item>
<item index="3" type="int64">4</item>
<item index="4" type="int64">5</item>
<item index="5" type="int64">6</item>
<item index="6" type="int64">7</item>
<item index="7" type="int64">8</item>
<item index="8" type="int64">9</item>
<item index="9" type="int64">9</item>
<item index="10" type="int64">9</item>
<item index="11" type="int64">9</item>
<item index="12" type="int64">9</item>
<item index="13" type="int64">9</item>
<item index="14" type="int64">9</item>
<item index="15" type="int64">9</item>
<item index="16" type="int64">9</item>
<item index="17" type="int64">9</item>
</material>
<name type="string">examp1003</name>
</item>
<item index="3">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">903</item>
</item>
<item index="3">
<add>
<item index="0" type="int64">7</item>
<item index="1" type="int64">100</item>
</add>
</item>
</attr>
<award1>
<item index="0" type="int64">1</item>
<item index="1" type="int64">2</item>
<item index="2" type="int64">3</item>
</award1>
<award2>
<id type="int64">1</id>
<num type="int64">3</num>
<type type="int64">2</type>
</award2>
<desc>
<item index="0" type="string">来源1</item>
<item index="1" type="string">来源2</item>
<item index="2" type="string">来源6</item>
</desc>
<id type="number">4</id>
<material>
<item index="0" type="string">测试数据</item>
<item index="1" type="string">测试数据2</item>
<item index="2" type="string">测试数据3</item>
</material>
<name type="string">examp1004</name>
</item>
<item index="4">
<attr>
<item index="0">
<item index="0" type="int64">1</item>
<item index="1" type="int64">700</item>
</item>
<item index="1">
<item index="0" type="int64">2</item>
<item index="1" type="int64">800</item>
</item>
<item index="2">
<item index="0" type="int64">3</item>
<item index="1" type="int64">903</item>
</item>
<item index="3">
<add>
<item index="0" type="int64">7</item>
<item index="1" type="int64">100</item>
</add>
</item>
</attr>
<award1>
<item index="0" type="int64">1</item>
<item index="1" type="int64">2</item>
<item index="2" type="int64">3</item>
</award1>
<award2>
<id type="int64">1</id>
<num type="int64">3</num>
<type type="int64">2</type>
</award2>
<desc>
<item index="0" type="string">来源1</item>
<item index="1" type="string">来源2</item>
<item index="2" type="string">来源6</item>
</desc>
<id type="number">5</id>
<material>
<item index="0" type="string">test</item>
</material>
<name type="string">examp1004</name>
</item>
</cfg_array_example2>

+ 4
- 0
client/cfg_array_example3.xml View File

@ -0,0 +1,4 @@
<?xml version="1.0" ?>
<cfg_array_example3>
<level type="string">啦啦啦!!!</level>
</cfg_array_example3>

+ 88
- 0
client/cfg_object.xml View File

@ -0,0 +1,88 @@
<?xml version="1.0" ?>
<cfg_object>
<actId type="number">1001</actId>
<add_value1 type="number">100.1</add_value1>
<add_value2 type="int64">100</add_value2>
<award1>
<item index="0">
<item index="0" type="int64">1001</item>
<item index="1" type="int64">20</item>
</item>
<item index="1">
<item index="0" type="int64">1002</item>
<item index="1" type="int64">20</item>
</item>
<item index="2">
<item index="0" type="int64">1003</item>
<item index="1" type="int64">30</item>
</item>
</award1>
<award2>
<item index="0">
<item index="0" type="int64">1001</item>
<item index="1" type="int64">10</item>
</item>
<item index="1">
<item index="0" type="int64">1002</item>
<item index="1" type="int64">20</item>
</item>
</award2>
<award4>
<aa>
<item index="0" type="int64">7003</item>
<item index="1" type="int64">1</item>
</aa>
<ff>
<item index="0" type="int64">3006</item>
<item index="1" type="int64">99</item>
</ff>
<rr>
<item index="0" type="int64">1001</item>
<item index="1" type="int64">20</item>
</rr>
<test type="string">这就是一个测试</test>
</award4>
<award6>
<item index="0">
<item index="0" type="int64">1001</item>
<item index="1" type="int64">20</item>
</item>
<item index="1">
<item index="0" type="int64">3006</item>
<item index="1" type="int64">99</item>
</item>
<item index="2">
<item index="0" type="int64">7003</item>
<item index="1" type="int64">1</item>
</item>
<item index="3">
<jsonobject>
<item index="0" type="int64">12356</item>
<item index="1" type="int64">654321</item>
</jsonobject>
</item>
</award6>
<award7>
<item index="0" type="int64">1</item>
<item index="1" type="int64">2</item>
<item index="2" type="int64">3</item>
<item index="3" type="int64">4</item>
<item index="4" type="int64">5</item>
<item index="5" type="int64">6</item>
<item index="6" type="int64">7</item>
<item index="7" type="int64">8</item>
<item index="8" type="int64">9</item>
<item index="9" type="int64">9</item>
<item index="10" type="int64">9</item>
<item index="11" type="int64">9</item>
<item index="12" type="int64">9</item>
<item index="13" type="int64">9</item>
<item index="14" type="int64">9</item>
<item index="15" type="int64">9</item>
<item index="16" type="int64">9</item>
<item index="17" type="int64">9</item>
</award7>
<jj10000 type="string">前面字段为errorID,这里是错误描述,是的object配置的server,client字段名还支持数字作为key(但是转出格式为xml和jsonarray时就不支持了)</jj10000>
<open type="string">18:00:0</open>
<open_level type="int64">90</open_level>
</cfg_object>

+ 88
- 0
client/cfg_object1_cfg_object.xml View File

@ -0,0 +1,88 @@
<?xml version="1.0" ?>
<cfg_object1_cfg_object>
<actId type="number">1001</actId>
<add_value1 type="number">100.1</add_value1>
<add_value2 type="int64">100</add_value2>
<award1>
<item index="0">
<item index="0" type="int64">1001</item>
<item index="1" type="int64">20</item>
</item>
<item index="1">
<item index="0" type="int64">1002</item>
<item index="1" type="int64">20</item>
</item>
<item index="2">
<item index="0" type="int64">1003</item>
<item index="1" type="int64">30</item>
</item>
</award1>
<award2>
<item index="0">
<item index="0" type="int64">1001</item>
<item index="1" type="int64">10</item>
</item>
<item index="1">
<item index="0" type="int64">1002</item>
<item index="1" type="int64">20</item>
</item>
</award2>
<award4>
<aa>
<item index="0" type="int64">7003</item>
<item index="1" type="int64">1</item>
</aa>
<ff>
<item index="0" type="int64">3006</item>
<item index="1" type="int64">99</item>
</ff>
<rr>
<item index="0" type="int64">1001</item>
<item index="1" type="int64">20</item>
</rr>
<test type="string">这就是一个测试</test>
</award4>
<award6>
<item index="0">
<item index="0" type="int64">1001</item>
<item index="1" type="int64">20</item>
</item>
<item index="1">
<item index="0" type="int64">3006</item>
<item index="1" type="int64">99</item>
</item>
<item index="2">
<item index="0" type="int64">7003</item>
<item index="1" type="int64">1</item>
</item>
<item index="3">
<jsonobject>
<item index="0" type="int64">12356</item>
<item index="1" type="int64">654321</item>
</jsonobject>
</item>
</award6>
<award7>
<item index="0" type="int64">1</item>
<item index="1" type="int64">2</item>
<item index="2" type="int64">3</item>
<item index="3" type="int64">4</item>
<item index="4" type="int64">5</item>
<item index="5" type="int64">6</item>
<item index="6" type="int64">7</item>
<item index="7" type="int64">8</item>
<item index="8" type="int64">9</item>
<item index="9" type="int64">9</item>
<item index="10" type="int64">9</item>
<item index="11" type="int64">9</item>
<item index="12" type="int64">9</item>
<item index="13" type="int64">9</item>
<item index="14" type="int64">9</item>
<item index="15" type="int64">9</item>
<item index="16" type="int64">9</item>
<item index="17" type="int64">9</item>
</award7>
<jj10000 type="string">前面字段为errorID,这里是错误描述,是的object配置的server,client字段名还支持数字作为key(但是转出格式为xml和jsonarray时就不支持了)</jj10000>
<open type="string">fgfdg</open>
<open_level type="int64">90</open_level>
</cfg_object1_cfg_object>

+ 219
- 0
color_print.py View File

@ -0,0 +1,219 @@
# -*- coding: gb2312 -*-
"""
"""
import ctypes
import sys
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# 字体颜色定义 ,关键在于颜色编码,由2位十六进制组成,分别取0~f,前一位指的是背景色,后一位指的是字体色
#由于该函数的限制,应该是只有这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.
# 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.
# 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
def resetColor():
set_cmd_text_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
###############################################################
#暗蓝色
#dark blue
def printDarkBlue(mess):
set_cmd_text_color(FOREGROUND_DARKBLUE)
sys.stdout.write(mess)
resetColor()
#暗绿色
#dark green
def printDarkGreen(mess):
set_cmd_text_color(FOREGROUND_DARKGREEN)
sys.stdout.write(mess)
resetColor()
#暗天蓝色
#dark sky blue
def printDarkSkyBlue(mess):
set_cmd_text_color(FOREGROUND_DARKSKYBLUE)
sys.stdout.write(mess)
resetColor()
#暗红色
#dark red
def printDarkRed(mess):
set_cmd_text_color(FOREGROUND_DARKRED)
sys.stdout.write(mess)
resetColor()
#暗粉红色
#dark pink
def printDarkPink(mess):
set_cmd_text_color(FOREGROUND_DARKPINK)
sys.stdout.write(mess)
resetColor()
#暗黄色
#dark yellow
def printDarkYellow(mess):
set_cmd_text_color(FOREGROUND_DARKYELLOW)
sys.stdout.write(mess)
resetColor()
#暗白色
#dark white
def printDarkWhite(mess):
set_cmd_text_color(FOREGROUND_DARKWHITE)
sys.stdout.write(mess)
resetColor()
#暗灰色
#dark gray
def printDarkGray(mess):
set_cmd_text_color(FOREGROUND_DARKGRAY)
sys.stdout.write(mess)
resetColor()
#蓝色
#blue
def printBlue(mess):
set_cmd_text_color(FOREGROUND_BLUE)
sys.stdout.write(mess)
resetColor()
#绿色
#green
def printGreen(mess):
set_cmd_text_color(FOREGROUND_GREEN)
sys.stdout.write(mess)
resetColor()
#天蓝色
#sky blue
def printSkyBlue(mess):
set_cmd_text_color(FOREGROUND_SKYBLUE)
sys.stdout.write(mess)
resetColor()
#红色
#red
def printRed(mess):
set_cmd_text_color(FOREGROUND_RED)
sys.stdout.write(mess)
resetColor()
#粉红色
#pink
def printPink(mess):
set_cmd_text_color(FOREGROUND_PINK)
sys.stdout.write(mess)
resetColor()
#黄色
#yellow
def printYellow(mess):
set_cmd_text_color(FOREGROUND_YELLOW)
sys.stdout.write(mess)
resetColor()
#白色
#white
def printWhite(mess):
set_cmd_text_color(FOREGROUND_WHITE)
sys.stdout.write(mess)
resetColor()
##################################################
#白底黑字
#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
def printWhiteBlack_2(mess):
set_cmd_text_color(0xf0)
sys.stdout.write(mess)
resetColor()
#黄底蓝字
#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' )

BIN
config_excel/A_array表示例--cfg_array.xlsx View File


BIN
config_excel/A_object表示例--cfg_object.xlsx View File


+ 442
- 0
decoder.py View File

@ -0,0 +1,442 @@
#! python
# -*- coding:utf-8 -*-
import os
import re
import sys
import json
import openpyxl
import color_print
from slpp.slpp import slpp as lua
# array数组模式下,各个栏的分布
# 1、2行是文档注释,不导出
ACMT_ROW = 3 # comment row 注释
ATPE_ROW = 4 # type row 类型
ASRV_ROW = 5 # server row 服务器
ACLT_ROW = 6 # client row 客户端
AKEY_COL = 1 # key column key所在列
# object(kv)模式下,各个栏的分布
OCMT_COL = 1 # comment column 注释
OTPE_COL = 2 # type column 类型
OSRV_COL = 3 # server column 服务器
OCLT_COL = 4 # client column 客户端
OCTX_COL = 5 # content column 内容所在列
# 1、2行是文档注释,不导出
OFLG_ROW = 3 # flag row server client所在行
SRV_FLAG = "server"
CLT_FLAG = "client"
SHEET_FLAG_ROW = 3 # 3列1行表示是array 还是object 或者是不用导出的表
SHEET_FLAG_COL = 1 # 3列1行表示是array 还是object 或者是不用导出的表
# 用于标识表的类型 不是这两种就不会导出数据
ARRAY_FLAG = "array" # 标识表的是array类型的表
OBJECT_FLAG = "object" # 标识表的是object类型的表
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 为python原生数据格式
# "json":8,"lua":9 为json和lua的数据格式
# excel配置的时候 对应类型字段 填入对应数据类型的有效数据格式的数据就OK
TYPES = { "int":1,"number":2,"int64":3,"string":4, "tuple":5, "list":6, "dict":7, "json":8,"lua":9}
try:
basestring
except NameError:
basestring = str
# python3中没有uincode了,int能表示int64
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 类型转换器
class ValueConverter(object):
def __init__(self):
pass
# 在python中,字符串和unicode是不一样的。默认从excel读取的数据都是unicode。
# str可以通过decode转换为unicode
# ascii' codec can't encode characters
# 这个函数在python3中没用
def to_unicode_str( self,val ):
if isinstance( val,str ) :
return val
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 :
# 去除带小数时的小数点,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 list(eval(val))
elif "dict" == val_type :
return dict(eval(val))
else :
self.raise_error( "invalid type",value )
class Sheet(object):
def __init__(self,base_name,wb_sheet,srv_writer,clt_writer):
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_keys = {} # 服务器key
self.clt_keys = {} # 客户端key
self.converter = ValueConverter()
self.wb_sheet = wb_sheet
self.base_name = 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" )
self.base_file_name = match_list[0]
# 记录出错时的行列,方便策划定位问题
self.error_row = 0
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 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 )
def to_value(self,val_type,val):
try:
return self.converter.to_value(val_type,val)
except Exception :
t, e = sys.exc_info()[:2]
self.raise_error( "ConverError",e )
# 解析一个表格
def decode_sheet(self):
wb_sheet = self.wb_sheet
self.decode_type ()
self.decode_field()
self.decode_ctx ()
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):
# 有些配置可能只导出客户端或只导出服务器
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 :
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]
wt = writer(self.base_name,self.wb_sheet.title, write_file_name, keys_list, comment_text)
ctx = wt.context( ctx )
suffix = wt.suffix()
if None != ctx :
path = base_path + write_file_name + suffix
#必须为wb,不然无法写入utf-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)
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 )
# 导出数组类型配置,A1格子的内容有array标识
class ArraySheet(Sheet):
def __init__(self,base_name,wb_sheet,srv_writer,clt_writer):
# 记录导出各行的内容
self.srv_ctx = []
self.clt_ctx = []
super( ArraySheet, self ).__init__(
base_name,wb_sheet,srv_writer,clt_writer )
# 解析各列的类型(string、number...)
def decode_type(self):
# 第一列没数据,类型可以不填,默认为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
# 单元格为空的时候,wb_sheet.cell(row=1, column=2).value == None
# 类型那一行必须连续,空白表示后面的数据都不导出了
if value == None :
break
if value not in TYPES :
self.raise_error( "invalid type",value )
self.types.append( value )
# 解析客户端、服务器的字段名(server、client)那两行
def decode_one_field(self,fields,row_index, keys):
key_index = 1
for col_index in range( AKEY_COL,len( self.types ) + 1 ):
value = self.wb_sheet.cell(
row = row_index, column = col_index ).value
# 对于array类型的表 一条数据可以有多个值作为KEY 需要处理一下
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为None
fields.append( value )
# 解析注释那一行
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
key = self.wb_sheet.cell(
row = key_index, column = col_index ).value
if None == key :
continue
# 对于不需要导出的field,可以为空。即value为None
if key.find(KEY_FLAG) >= 0 :
key = key[KEY_FLAG_LEN:]
fields[key] = value
else :
fields[key] = value
# 导出客户端、服务端字段名(server、client)那一列
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_comment( self.srv_comment, ACMT_ROW, ASRV_ROW)
self.decode_one_comment( self.clt_comment, ACMT_ROW, ACLT_ROW)
# 解析出一个格子的内容
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 )
# 解析出一行的内容
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
srv_key = self.srv_fields[col_idx - 1]
clt_key = self.clt_fields[col_idx - 1]
if srv_key :
srv_row[srv_key] = value
if clt_key :
clt_row[clt_key] = value
return srv_row,clt_row # 返回一个tuple
# 解析导出的内容
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 )
if row_idx > 57 :
break
# 不为空才追加
if any( srv_row ) :
self.srv_ctx.append( srv_row )
if any( clt_row ) :
self.clt_ctx.append( clt_row )
# 导出object类型的结构,A1格子有object标识
class ObjectSheet(Sheet):
def __init__(self,base_name,wb_sheet,srv_writer,clt_writer):
# 记录导出各行的内容
self.srv_ctx = {}
self.clt_ctx = {}
super( ObjectSheet, self ).__init__(
base_name,wb_sheet,srv_writer,clt_writer )
# 解析各字段的类型
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
# 类型必须连续,遇到空则认为后续数据不再导出
if value == None :
break
if value not in TYPES :
self.raise_error( "invalid type",value )
self.types.append( value )
# 导出客户端、服务端字段名(server、client)那一列
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为None
fields.append( 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
if None == value:
continue
# 导出存在值的fields的注释
fields[key] = value
# 导出客户端、服务端字段名(server、client)那一列
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_comment( self.srv_comment, OCMT_COL, OSRV_COL)
self.decode_one_comment( self.clt_comment, OCMT_COL, OCLT_COL )
# 解析一个单元格内容
def decode_cell(self,row_idx):
value = self.wb_sheet.cell( row = row_idx, column = OCTX_COL ).value
if None == value : return None
# 在object的结构中,数据是从第二行开始的,所以types的下标偏移2
self.mark_error_pos( row_idx,OCTX_COL )
return self.to_value( self.types[row_idx - OFLG_ROW - 1],value )
# 解析表格的所有内容
def decode_ctx(self):
for row_idx in range( OFLG_ROW + 1,len( self.types ) + OFLG_ROW + 1 ):
value = self.decode_cell( row_idx )
if row_idx > 54 :
break
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
class ExcelDoc:
def __init__(self, file,abspath):
self.file = file
self.abspath = abspath
# 是否需要解析
# 返回解析的对象类型
def need_decode(self,wb_sheet):
sheet_val = wb_sheet.cell(
row = SHEET_FLAG_ROW, column = SHEET_FLAG_COL ).value
sheeter = None
srv_value = None
clt_value = None
if ARRAY_FLAG == sheet_val :
if wb_sheet.max_row <= ACLT_ROW or wb_sheet.max_column <= AKEY_COL:
return None
sheeter = ArraySheet
srv_value = wb_sheet.cell( row = ASRV_ROW, column = AKEY_COL ).value
clt_value = wb_sheet.cell( row = ACLT_ROW, column = AKEY_COL ).value
elif OBJECT_FLAG == sheet_val :
sheeter = ObjectSheet
srv_value = wb_sheet.cell( row = OFLG_ROW, column = OSRV_COL ).value
clt_value = wb_sheet.cell( row = OFLG_ROW, column = OCLT_COL ).value
else :
return None
# 没有这两个标识就不是配置表。可能是策划的一些备注说明
if SRV_FLAG != srv_value or CLT_FLAG != clt_value :
return None
return sheeter
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 )
for wb_sheet in wb.worksheets:
Sheeter = 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 )
if sheet.decode_sheet() :
sheet.write_files( srv_path,clt_path )

+ 12
- 0
lancher.bat View File

@ -0,0 +1,12 @@
@echo off
:python ConfigConvertTool.py --input ./config_excel --srv server/ --clt client/ --timeout -1 --suffix .xlsx --swriter lua --cwriter lua
:python ConfigConvertTool.py --input ./config_excel --srv server/ --clt client/ --timeout -1 --suffix .xlsx --swriter erlanghrl
:python ConfigConvertTool.py --input ./config_excel --srv server/ --clt client/ --timeout -1 --suffix .xlsx --swriter erlangerl
:python ConfigConvertTool.py --input ./config_excel --srv server/ --clt client/ --timeout -1 --suffix .xlsx --swriter elixir
:python ConfigConvertTool.py --input ./config_excel --srv server/ --clt client/ --timeout -1 --suffix .xlsx --swriter jsonobject
:python ConfigConvertTool.py --input ./config_excel --srv server/ --clt client/ --timeout -1 --suffix .xlsx --cwriter jsonarray
python ConfigConvertTool.py --input ./config_excel --srv server/ --clt client/ --timeout -1 --suffix .xlsx --swriter elixir --cwriter xml
pause

+ 6
- 0
lancher.sh View File

@ -0,0 +1,6 @@
#!/bin/bash
python reader.py --input ./ --srv server/ --clt client/ --timeout -1 --suffix .xlsx --swriter lua --cwriter json
python reader.py --input ./ --srv server/ --clt client/ --timeout -1 --suffix .xlsx --cwriter xml
python reader.py --input ./ --srv server/ --clt client/ --timeout -1 --suffix .xlsx --cwriter lua

+ 14
- 0
server/cfg_array.erl View File

@ -0,0 +1,14 @@
%% Automatic generation from -->>
%% excel file name : A_object表示例--cfg_array
%% excel sheet name : +example3
-module(cfg_array).
-compile(export_all).
%%
get('level') ->
"啦啦啦!!!";
get(_) ->
undefined.

+ 16
- 0
server/cfg_array.ex View File

@ -0,0 +1,16 @@
## Automatic generation from -->>
## excel file name: A_object表示例--cfg_array
## excel sheet name: +example3
defmodule Cfg_Array do
## 演示
def get(:level) do
"啦啦啦!!!"
end
def get(_) do
:undefined
end
end

+ 3
- 0
server/cfg_array.json View File

@ -0,0 +1,3 @@
{
"level":"啦啦啦!!!"
}

+ 10
- 0
server/cfg_array.lua View File

@ -0,0 +1,10 @@
-- Automatic generation from -->>
-- excel file name: A_object表示例--cfg_array
-- excel sheet name: +example3
local cfg_array =
{
-- 演示
level = '啦啦啦!!!'
}
return cfg_array

+ 311
- 0
server/cfg_array_example1.erl View File

@ -0,0 +1,311 @@
%% Automatic generation from -->>
%% excel file name : A_array表示例--cfg_array
%% excel sheet name : 1-example1
-module(cfg_array_example1).
-include("cfg_array_example1.hrl").
-compile(export_all).
get(1001, "pos1", 88, 1) ->
#cfg_array_example1{
'id' = 1001
,'str' = "pos1"
,'level' = 88
,'sub_level' = 1
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 900]]
,'desc1' = "从小城镇"
};
get(1001, "pos1", 88, 2) ->
#cfg_array_example1{
'id' = 1001
,'str' = "pos1"
,'level' = 88
,'sub_level' = 2
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 900]]
,'desc1' = "有钱就可以买"
};
get(1001, "pos1", 89, 89) ->
#cfg_array_example1{
'id' = 1001
,'str' = "pos1"
,'level' = 89
,'sub_level' = 89
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 900]]
,'desc1' = "有钱就可以买"
};
get(1001, "pos2", 88, 88.9) ->
#cfg_array_example1{
'id' = 1001
,'str' = "pos2"
,'level' = 88
,'sub_level' = 88.9
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 900]]
,'desc1' = "有钱就可以买"
};
get(1001, "pos2", 89, 89) ->
#cfg_array_example1{
'id' = 1001
,'str' = "pos2"
,'level' = 89
,'sub_level' = 89
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 900]]
,'desc1' = "有钱就可以买"
};
get(1002, "pos1", 88, 88) ->
#cfg_array_example1{
'id' = 1002
,'str' = "pos1"
,'level' = 88
,'sub_level' = 88
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 901]]
,'desc1' = "有钱就可以买"
};
get(1002, "pos1", 89, 89) ->
#cfg_array_example1{
'id' = 1002
,'str' = "pos1"
,'level' = 89
,'sub_level' = 89
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 900]]
,'desc1' = "有钱就可以买"
};
get(1002, "pos1", 90, 90) ->
#cfg_array_example1{
'id' = 1002
,'str' = "pos1"
,'level' = 90
,'sub_level' = 90
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 901]]
,'desc1' = "有钱就可以买"
};
get(1002, "pos2", 88, 88) ->
#cfg_array_example1{
'id' = 1002
,'str' = "pos2"
,'level' = 88
,'sub_level' = 88
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 901]]
,'desc1' = "有钱就可以买"
};
get(1002, "pos2", 89, 89) ->
#cfg_array_example1{
'id' = 1002
,'str' = "pos2"
,'level' = 89
,'sub_level' = 89
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 900]]
,'desc1' = "有钱就可以买"
};
get(1002, "pos2", 90, 90) ->
#cfg_array_example1{
'id' = 1002
,'str' = "pos2"
,'level' = 90
,'sub_level' = 90
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 901]]
,'desc1' = "有钱就可以买"
};
get(1003, "pos1", 85, 85) ->
#cfg_array_example1{
'id' = 1003
,'str' = "pos1"
,'level' = 85
,'sub_level' = 85
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 902]]
,'desc1' = "有钱就可以买"
};
get(1004, "pos1", 80, 80) ->
#cfg_array_example1{
'id' = 1004
,'str' = "pos1"
,'level' = 80
,'sub_level' = 80
,'name' = "黑切+蓝盾"
,'attr' = [[1, 700], [2, 800], [3, 903]]
,'desc1' = "有钱就可以买"
};
get(_, _, _, _) ->
undefined.
get_all() ->
[
{1001, "pos1", 88, 1}
,{1001, "pos1", 88, 2}
,{1001, "pos1", 89, 89}
,{1001, "pos2", 88, 88.9}
,{1001, "pos2", 89, 89}
,{1002, "pos1", 88, 88}
,{1002, "pos1", 89, 89}
,{1002, "pos1", 90, 90}
,{1002, "pos2", 88, 88}
,{1002, "pos2", 89, 89}
,{1002, "pos2", 90, 90}
,{1003, "pos1", 85, 85}
,{1004, "pos1", 80, 80}
].
get_list() ->
get_all().
get_list(1001) ->
[
{1001, "pos1", 88, 1}
,{1001, "pos1", 88, 2}
,{1001, "pos1", 89, 89}
,{1001, "pos2", 88, 88.9}
,{1001, "pos2", 89, 89}
];
get_list(1002) ->
[
{1002, "pos1", 88, 88}
,{1002, "pos1", 89, 89}
,{1002, "pos1", 90, 90}
,{1002, "pos2", 88, 88}
,{1002, "pos2", 89, 89}
,{1002, "pos2", 90, 90}
];
get_list(1003) ->
[
{1003, "pos1", 85, 85}
];
get_list(1004) ->
[
{1004, "pos1", 80, 80}
];
get_list(_) ->
[].
get_list(1001, "pos1") ->
[
{1001, "pos1", 88, 1}
,{1001, "pos1", 88, 2}
,{1001, "pos1", 89, 89}
];
get_list(1001, "pos2") ->
[
{1001, "pos2", 88, 88.9}
,{1001, "pos2", 89, 89}
];
get_list(1002, "pos1") ->
[
{1002, "pos1", 88, 88}
,{1002, "pos1", 89, 89}
,{1002, "pos1", 90, 90}
];
get_list(1002, "pos2") ->
[
{1002, "pos2", 88, 88}
,{1002, "pos2", 89, 89}
,{1002, "pos2", 90, 90}
];
get_list(1003, "pos1") ->
[
{1003, "pos1", 85, 85}
];
get_list(1004, "pos1") ->
[
{1004, "pos1", 80, 80}
];
get_list(_, _) ->
[].
get_list(1001, "pos1", 88) ->
[
{1001, "pos1", 88, 1}
,{1001, "pos1", 88, 2}
];
get_list(1001, "pos1", 89) ->
[
{1001, "pos1", 89, 89}
];
get_list(1001, "pos2", 88) ->
[
{1001, "pos2", 88, 88.9}
];
get_list(1001, "pos2", 89) ->
[
{1001, "pos2", 89, 89}
];
get_list(1002, "pos1", 88) ->
[
{1002, "pos1", 88, 88}
];
get_list(1002, "pos1", 89) ->
[
{1002, "pos1", 89, 89}
];
get_list(1002, "pos1", 90) ->
[
{1002, "pos1", 90, 90}
];
get_list(1002, "pos2", 88) ->
[
{1002, "pos2", 88, 88}
];
get_list(1002, "pos2", 89) ->
[
{1002, "pos2", 89, 89}
];
get_list(1002, "pos2", 90) ->
[
{1002, "pos2", 90, 90}
];
get_list(1003, "pos1", 85) ->
[
{1003, "pos1", 85, 85}
];
get_list(1004, "pos1", 80) ->
[
{1004, "pos1", 80, 80}
];
get_list(_, _, _) ->
[].

+ 360
- 0
server/cfg_array_example1.ex View File

@ -0,0 +1,360 @@
## Automatic generation from -->>
## excel file name: A_array表示例--cfg_array
## excel sheet name: 示例1-example1
defmodule Cfg_Array_Example1 do
defstruct [
:id, ## 唯一id
:str, ## 佩戴位置
:level, ## 等级
:sub_level, ## 等级
:name, ## 装备名字
:attr, ## 装备增加属性
:desc1 ## 装备来源描述
]
def get(1001, "pos1", 88, 1) do
%Cfg_Array_Example1{
:id => 1001,
:str => "pos1",
:level => 88,
:sub_level => 1,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 900]],
:desc1 => "从小城镇"
}
end
def get(1001, "pos1", 88, 2) do
%Cfg_Array_Example1{
:id => 1001,
:str => "pos1",
:level => 88,
:sub_level => 2,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 900]],
:desc1 => "有钱就可以买"
}
end
def get(1001, "pos1", 89, 89) do
%Cfg_Array_Example1{
:id => 1001,
:str => "pos1",
:level => 89,
:sub_level => 89,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 900]],
:desc1 => "有钱就可以买"
}
end
def get(1001, "pos2", 88, 88.9) do
%Cfg_Array_Example1{
:id => 1001,
:str => "pos2",
:level => 88,
:sub_level => 88.9,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 900]],
:desc1 => "有钱就可以买"
}
end
def get(1001, "pos2", 89, 89) do
%Cfg_Array_Example1{
:id => 1001,
:str => "pos2",
:level => 89,
:sub_level => 89,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 900]],
:desc1 => "有钱就可以买"
}
end
def get(1002, "pos1", 88, 88) do
%Cfg_Array_Example1{
:id => 1002,
:str => "pos1",
:level => 88,
:sub_level => 88,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 901]],
:desc1 => "有钱就可以买"
}
end
def get(1002, "pos1", 89, 89) do
%Cfg_Array_Example1{
:id => 1002,
:str => "pos1",
:level => 89,
:sub_level => 89,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 900]],
:desc1 => "有钱就可以买"
}
end
def get(1002, "pos1", 90, 90) do
%Cfg_Array_Example1{
:id => 1002,
:str => "pos1",
:level => 90,
:sub_level => 90,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 901]],
:desc1 => "有钱就可以买"
}
end
def get(1002, "pos2", 88, 88) do
%Cfg_Array_Example1{
:id => 1002,
:str => "pos2",
:level => 88,
:sub_level => 88,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 901]],
:desc1 => "有钱就可以买"
}
end
def get(1002, "pos2", 89, 89) do
%Cfg_Array_Example1{
:id => 1002,
:str => "pos2",
:level => 89,
:sub_level => 89,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 900]],
:desc1 => "有钱就可以买"
}
end
def get(1002, "pos2", 90, 90) do
%Cfg_Array_Example1{
:id => 1002,
:str => "pos2",
:level => 90,
:sub_level => 90,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 901]],
:desc1 => "有钱就可以买"
}
end
def get(1003, "pos1", 85, 85) do
%Cfg_Array_Example1{
:id => 1003,
:str => "pos1",
:level => 85,
:sub_level => 85,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 902]],
:desc1 => "有钱就可以买"
}
end
def get(1004, "pos1", 80, 80) do
%Cfg_Array_Example1{
:id => 1004,
:str => "pos1",
:level => 80,
:sub_level => 80,
:name => "黑切+蓝盾",
:attr => [[1, 700], [2, 800], [3, 903]],
:desc1 => "有钱就可以买"
}
end
def get(_, _, _, _) do
:undefined
end
def get_all() do
[
{1001, "pos1", 88, 1},
{1001, "pos1", 88, 2},
{1001, "pos1", 89, 89},
{1001, "pos2", 88, 88.9},
{1001, "pos2", 89, 89},
{1002, "pos1", 88, 88},
{1002, "pos1", 89, 89},
{1002, "pos1", 90, 90},
{1002, "pos2", 88, 88},
{1002, "pos2", 89, 89},
{1002, "pos2", 90, 90},
{1003, "pos1", 85, 85},
{1004, "pos1", 80, 80}
]
end
def get_list() do
get_all()
end
def get_list(1001) do
[
{1001, "pos1", 88, 1},
{1001, "pos1", 88, 2},
{1001, "pos1", 89, 89},
{1001, "pos2", 88, 88.9},
{1001, "pos2", 89, 89}
]
end
def get_list(1002) do
[
{1002, "pos1", 88, 88},
{1002, "pos1", 89, 89},
{1002, "pos1", 90, 90},
{1002, "pos2", 88, 88},
{1002, "pos2", 89, 89},
{1002, "pos2", 90, 90}
]
end
def get_list(1003) do
[
{1003, "pos1", 85, 85}
]
end
def get_list(1004) do
[
{1004, "pos1", 80, 80}
]
end
def get_list(_) do
[]
end
def get_list(1001, "pos1") do
[
{1001, "pos1", 88, 1},
{1001, "pos1", 88, 2},
{1001, "pos1", 89, 89}
]
end
def get_list(1001, "pos2") do
[
{1001, "pos2", 88, 88.9},
{1001, "pos2", 89, 89}
]
end
def get_list(1002, "pos1") do
[
{1002, "pos1", 88, 88},
{1002, "pos1", 89, 89},
{1002, "pos1", 90, 90}
]
end
def get_list(1002, "pos2") do
[
{1002, "pos2", 88, 88},
{1002, "pos2", 89, 89},
{1002, "pos2", 90, 90}
]
end
def get_list(1003, "pos1") do
[
{1003, "pos1", 85, 85}
]
end
def get_list(1004, "pos1") do
[
{1004, "pos1", 80, 80}
]
end
def get_list(_, _) do
[]
end
def get_list(1001, "pos1", 88) do
[
{1001, "pos1", 88, 1},
{1001, "pos1", 88, 2}
]
end
def get_list(1001, "pos1", 89) do
[
{1001, "pos1", 89, 89}
]
end
def get_list(1001, "pos2", 88) do
[
{1001, "pos2", 88, 88.9}
]
end
def get_list(1001, "pos2", 89) do
[
{1001, "pos2", 89, 89}
]
end
def get_list(1002, "pos1", 88) do
[
{1002, "pos1", 88, 88}
]
end
def get_list(1002, "pos1", 89) do
[
{1002, "pos1", 89, 89}
]
end
def get_list(1002, "pos1", 90) do
[
{1002, "pos1", 90, 90}
]
end
def get_list(1002, "pos2", 88) do
[
{1002, "pos2", 88, 88}
]
end
def get_list(1002, "pos2", 89) do
[
{1002, "pos2", 89, 89}
]
end
def get_list(1002, "pos2", 90) do
[
{1002, "pos2", 90, 90}
]
end
def get_list(1003, "pos1", 85) do
[
{1003, "pos1", 85, 85}
]
end
def get_list(1004, "pos1", 80) do
[
{1004, "pos1", 80, 80}
]
end
def get_list(_, _, _) do
[]
end
end

+ 13
- 0
server/cfg_array_example1.hrl View File

@ -0,0 +1,13 @@
%% Automatic generation from -->>
%% excel file name : A_array表示例--cfg_array
%% excel sheet name : 1-example1
-record(cfg_array_example1, {
'id' %% id
,'str' %%
,'level' %%
,'sub_level' %%
,'name' %%
,'attr' %%
,'desc1' %%
}).

+ 332
- 0
server/cfg_array_example1.json View File

@ -0,0 +1,332 @@
{
"1001":{
"pos1":{
"88":{
"1":{
"id":1001,
"str":"pos1",
"level":88,
"sub_level":1,
"name":"黑切+蓝盾",
"desc1":"从小城镇",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
900
]
]
},
"2":{
"id":1001,
"str":"pos1",
"level":88,
"sub_level":2,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
900
]
]
}
},
"89":{
"89":{
"id":1001,
"str":"pos1",
"level":89,
"sub_level":89,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
900
]
]
}
}
},
"pos2":{
"88":{
"88.9":{
"id":1001,
"str":"pos2",
"level":88,
"sub_level":88.9,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
900
]
]
}
},
"89":{
"89":{
"id":1001,
"str":"pos2",
"level":89,
"sub_level":89,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
900
]
]
}
}
}
},
"1002":{
"pos1":{
"88":{
"88":{
"id":1002,
"str":"pos1",
"level":88,
"sub_level":88,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
901
]
]
}
},
"89":{
"89":{
"id":1002,
"str":"pos1",
"level":89,
"sub_level":89,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
900
]
]
}
},
"90":{
"90":{
"id":1002,
"str":"pos1",
"level":90,
"sub_level":90,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
901
]
]
}
}
},
"pos2":{
"88":{
"88":{
"id":1002,
"str":"pos2",
"level":88,
"sub_level":88,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
901
]
]
}
},
"89":{
"89":{
"id":1002,
"str":"pos2",
"level":89,
"sub_level":89,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
900
]
]
}
},
"90":{
"90":{
"id":1002,
"str":"pos2",
"level":90,
"sub_level":90,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
901
]
]
}
}
}
},
"1003":{
"pos1":{
"85":{
"85":{
"id":1003,
"str":"pos1",
"level":85,
"sub_level":85,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
902
]
]
}
}
}
},
"1004":{
"pos1":{
"80":{
"80":{
"id":1004,
"str":"pos1",
"level":80,
"sub_level":80,
"name":"黑切+蓝盾",
"desc1":"有钱就可以买",
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
903
]
]
}
}
}
}
}

+ 433
- 0
server/cfg_array_example1.lua View File

@ -0,0 +1,433 @@
-- Automatic generation from -->>
-- excel file name: A_array表示例--cfg_array
-- excel sheet name: 示例1-example1
local cfg_array_example1 =
--: id ## 唯一id
--: str ## 佩戴位置
--: level ## 等级
--: sub_level ## 等级
--: name ## 装备名字
--: attr ## 装备增加属性
--: desc1 ## 装备来源描述
{
[1001] =
{
pos1 =
{
[88] =
{
[1] =
{
id = 1001,
str = 'pos1',
level = 88,
sub_level = 1,
name = '黑切+蓝盾',
desc1 = '从小城镇',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 900
}
}
},
[2] =
{
id = 1001,
str = 'pos1',
level = 88,
sub_level = 2,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 900
}
}
}
},
[89] =
{
[89] =
{
id = 1001,
str = 'pos1',
level = 89,
sub_level = 89,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 900
}
}
}
}
},
pos2 =
{
[88] =
{
[88.9] =
{
id = 1001,
str = 'pos2',
level = 88,
sub_level = 88.9,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 900
}
}
}
},
[89] =
{
[89] =
{
id = 1001,
str = 'pos2',
level = 89,
sub_level = 89,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 900
}
}
}
}
}
},
[1002] =
{
pos1 =
{
[88] =
{
[88] =
{
id = 1002,
str = 'pos1',
level = 88,
sub_level = 88,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 901
}
}
}
},
[89] =
{
[89] =
{
id = 1002,
str = 'pos1',
level = 89,
sub_level = 89,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 900
}
}
}
},
[90] =
{
[90] =
{
id = 1002,
str = 'pos1',
level = 90,
sub_level = 90,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 901
}
}
}
}
},
pos2 =
{
[88] =
{
[88] =
{
id = 1002,
str = 'pos2',
level = 88,
sub_level = 88,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 901
}
}
}
},
[89] =
{
[89] =
{
id = 1002,
str = 'pos2',
level = 89,
sub_level = 89,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 900
}
}
}
},
[90] =
{
[90] =
{
id = 1002,
str = 'pos2',
level = 90,
sub_level = 90,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 901
}
}
}
}
}
},
[1003] =
{
pos1 =
{
[85] =
{
[85] =
{
id = 1003,
str = 'pos1',
level = 85,
sub_level = 85,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 902
}
}
}
}
}
},
[1004] =
{
pos1 =
{
[80] =
{
[80] =
{
id = 1004,
str = 'pos1',
level = 80,
sub_level = 80,
name = '黑切+蓝盾',
desc1 = '有钱就可以买',
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 903
}
}
}
}
}
}
}
return cfg_array_example1

+ 74
- 0
server/cfg_array_example2.erl View File

@ -0,0 +1,74 @@
%% Automatic generation from -->>
%% excel file name : A_array表示例--cfg_array
%% excel sheet name : 2+example2
-module(cfg_array_example2).
-include("cfg_array_example2.hrl").
-compile(export_all).
get(1) ->
#cfg_array_example2{
'id' = 1
,'name' = "examp1001"
,'material' = [#{'res' => 1, 'id' => 10001, 'count' => 1}, #{'res' => 1, 'id' => 10001, 'count' => 1}]
,'attr' = [[1, 700], [2, 800], [3, 900], #{'add' => [4, 100]}]
,'award1' = {1, 2, 3}
,'award2' = #{'id' => 1, 'type' => 2, 'num' => 3}
};
get(2) ->
#cfg_array_example2{
'id' = 2
,'name' = "examp1002"
,'material' = #{'res' => 1, 'id' => 10001, 'count' => 1}
,'attr' = [[1, 700], [2, 800], [3, 901], #{'add' => [5, 100]}]
,'award1' = {1, 2, 3}
,'award2' = #{'id' => 1, 'type' => 2, 'num' => 3}
};
get(3) ->
#cfg_array_example2{
'id' = 3
,'name' = "examp1003"
,'material' = [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
,'attr' = [[1, 700], [2, 800], [3, 902], #{'add' => [6, 100]}]
,'award1' = {1, 2, 3}
,'award2' = #{'id' => 1, 'type' => 2, 'num' => 3}
};
get(4) ->
#cfg_array_example2{
'id' = 4
,'name' = "examp1004"
,'material' = ["测试数据", "测试数据2", "测试数据3"]
,'attr' = [[1, 700], [2, 800], [3, 903], #{'add' => [7, 100]}]
,'award1' = {1, 2, 3}
,'award2' = #{'id' => 1, 'type' => 2, 'num' => 3}
};
get(5) ->
#cfg_array_example2{
'id' = 5
,'name' = "examp1004"
,'material' = ["test"]
,'attr' = [[1, 700], [2, 800], [3, 903], #{'add' => [7, 100]}]
,'award1' = {1, 2, 3}
,'award2' = #{'id' => 1, 'type' => 2, 'num' => 3}
};
get(_) ->
undefined.
get_all() ->
[
{1}
,{2}
,{3}
,{4}
,{5}
].
get_list() ->
get_all().

+ 89
- 0
server/cfg_array_example2.ex View File

@ -0,0 +1,89 @@
## Automatic generation from -->>
## excel file name: A_array表示例--cfg_array
## excel sheet name: 示例2+example2
defmodule Cfg_Array_Example2 do
defstruct [
:id, ## 英雄id
:name, ## 英雄名字
:material, ## 合成消耗
:attr, ## 属性
:award1, ## 奖励1
:award2 ## 奖励2
]
def get(1) do
%Cfg_Array_Example2{
:id => 1,
:name => "examp1001",
:material => [%{:res => 1, :id => 10001, :count => 1}, %{:res => 1, :id => 10001, :count => 1}],
:attr => [[1, 700], [2, 800], [3, 900], %{:add => [4, 100]}],
:award1 => {1, 2, 3},
:award2 => %{:id => 1, :type => 2, :num => 3}
}
end
def get(2) do
%Cfg_Array_Example2{
:id => 2,
:name => "examp1002",
:material => %{:res => 1, :id => 10001, :count => 1},
:attr => [[1, 700], [2, 800], [3, 901], %{:add => [5, 100]}],
:award1 => {1, 2, 3},
:award2 => %{:id => 1, :type => 2, :num => 3}
}
end
def get(3) do
%Cfg_Array_Example2{
:id => 3,
:name => "examp1003",
:material => [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
:attr => [[1, 700], [2, 800], [3, 902], %{:add => [6, 100]}],
:award1 => {1, 2, 3},
:award2 => %{:id => 1, :type => 2, :num => 3}
}
end
def get(4) do
%Cfg_Array_Example2{
:id => 4,
:name => "examp1004",
:material => ["测试数据", "测试数据2", "测试数据3"],
:attr => [[1, 700], [2, 800], [3, 903], %{:add => [7, 100]}],
:award1 => {1, 2, 3},
:award2 => %{:id => 1, :type => 2, :num => 3}
}
end
def get(5) do
%Cfg_Array_Example2{
:id => 5,
:name => "examp1004",
:material => ["test"],
:attr => [[1, 700], [2, 800], [3, 903], %{:add => [7, 100]}],
:award1 => {1, 2, 3},
:award2 => %{:id => 1, :type => 2, :num => 3}
}
end
def get(_) do
:undefined
end
def get_all() do
[
{1},
{2},
{3},
{4},
{5}
]
end
def get_list() do
get_all()
end
end

+ 12
- 0
server/cfg_array_example2.hrl View File

@ -0,0 +1,12 @@
%% Automatic generation from -->>
%% excel file name : A_array表示例--cfg_array
%% excel sheet name : 2+example2
-record(cfg_array_example2, {
'id' %% id
,'name' %%
,'material' %%
,'attr' %%
,'award1' %% 1
,'award2' %% 2
}).

+ 217
- 0
server/cfg_array_example2.json View File

@ -0,0 +1,217 @@
{
"1":{
"id":1,
"name":"examp1001",
"material":[
{
"res":1,
"id":10001,
"count":1
},
{
"res":1,
"id":10001,
"count":1
}
],
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
900
],
{
"add":[
4,
100
]
}
],
"award1":[
1,
2,
3
],
"award2":{
"id":1,
"type":2,
"num":3
}
},
"2":{
"id":2,
"name":"examp1002",
"material":{
"res":1,
"id":10001,
"count":1
},
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
901
],
{
"add":[
5,
100
]
}
],
"award1":[
1,
2,
3
],
"award2":{
"id":1,
"type":2,
"num":3
}
},
"3":{
"id":3,
"name":"examp1003",
"material":[
1,
2,
3,
4,
5,
6,
7,
8,
9,
9,
9,
9,
9,
9,
9,
9,
9,
9
],
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
902
],
{
"add":[
6,
100
]
}
],
"award1":[
1,
2,
3
],
"award2":{
"id":1,
"type":2,
"num":3
}
},
"4":{
"id":4,
"name":"examp1004",
"material":[
"测试数据",
"测试数据2",
"测试数据3"
],
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
903
],
{
"add":[
7,
100
]
}
],
"award1":[
1,
2,
3
],
"award2":{
"id":1,
"type":2,
"num":3
}
},
"5":{
"id":5,
"name":"examp1004",
"material":[
"test"
],
"attr":[
[
1,
700
],
[
2,
800
],
[
3,
903
],
{
"add":[
7,
100
]
}
],
"award1":[
1,
2,
3
],
"award2":{
"id":1,
"type":2,
"num":3
}
}
}

+ 282
- 0
server/cfg_array_example2.lua View File

@ -0,0 +1,282 @@
-- Automatic generation from -->>
-- excel file name: A_array表示例--cfg_array
-- excel sheet name: 示例2+example2
local cfg_array_example2 =
--: id ## 英雄id
--: name ## 英雄名字
--: material ## 合成消耗
--: attr ## 属性
--: award1 ## 奖励1
--: award2 ## 奖励2
{
[1] =
{
id = 1,
name = 'examp1001',
material =
{
[1] =
{
res = 1,
id = 10001,
count = 1
},
[2] =
{
res = 1,
id = 10001,
count = 1
}
},
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 900
},
[4] =
{
add =
{
[1] = 4,
[2] = 100
}
}
},
award1 =
{
[1] = 1,
[2] = 2,
[3] = 3
},
award2 =
{
id = 1,
type = 2,
num = 3
}
},
[2] =
{
id = 2,
name = 'examp1002',
material =
{
res = 1,
id = 10001,
count = 1
},
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 901
},
[4] =
{
add =
{
[1] = 5,
[2] = 100
}
}
},
award1 =
{
[1] = 1,
[2] = 2,
[3] = 3
},
award2 =
{
id = 1,
type = 2,
num = 3
}
},
[3] =
{
id = 3,
name = 'examp1003',
material =
{
[1] = 1,
[2] = 2,
[3] = 3,
[4] = 4,
[5] = 5,
[6] = 6,
[7] = 7,
[8] = 8,
[9] = 9,
[10] = 9,
[11] = 9,
[12] = 9,
[13] = 9,
[14] = 9,
[15] = 9,
[16] = 9,
[17] = 9,
[18] = 9
},
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 902
},
[4] =
{
add =
{
[1] = 6,
[2] = 100
}
}
},
award1 =
{
[1] = 1,
[2] = 2,
[3] = 3
},
award2 =
{
id = 1,
type = 2,
num = 3
}
},
[4] =
{
id = 4,
name = 'examp1004',
material =
{
[1] = '测试数据',
[2] = '测试数据2',
[3] = '测试数据3'
},
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 903
},
[4] =
{
add =
{
[1] = 7,
[2] = 100
}
}
},
award1 =
{
[1] = 1,
[2] = 2,
[3] = 3
},
award2 =
{
id = 1,
type = 2,
num = 3
}
},
[5] =
{
id = 5,
name = 'examp1004',
material =
{
[1] = 'test'
},
attr =
{
[1] =
{
[1] = 1,
[2] = 700
},
[2] =
{
[1] = 2,
[2] = 800
},
[3] =
{
[1] = 3,
[2] = 903
},
[4] =
{
add =
{
[1] = 7,
[2] = 100
}
}
},
award1 =
{
[1] = 1,
[2] = 2,
[3] = 3
},
award2 =
{
id = 1,
type = 2,
num = 3
}
}
}
return cfg_array_example2

+ 14
- 0
server/cfg_array_example3.erl View File

@ -0,0 +1,14 @@
%% Automatic generation from -->>
%% excel file name : A_array表示例--cfg_array
%% excel sheet name : +example3
-module(cfg_array_example3).
-compile(export_all).
%%
get('level') ->
"啦啦啦!!!";
get(_) ->
undefined.

+ 16
- 0
server/cfg_array_example3.ex View File

@ -0,0 +1,16 @@
## Automatic generation from -->>
## excel file name: A_array表示例--cfg_array
## excel sheet name: +example3
defmodule Cfg_Array_Example3 do
## 演示
def get(:level) do
"啦啦啦!!!"
end
def get(_) do
:undefined
end
end

+ 3
- 0
server/cfg_array_example3.json View File

@ -0,0 +1,3 @@
{
"level":"啦啦啦!!!"
}

+ 10
- 0
server/cfg_array_example3.lua View File

@ -0,0 +1,10 @@
-- Automatic generation from -->>
-- excel file name: A_array表示例--cfg_array
-- excel sheet name: +example3
local cfg_array_example3 =
{
-- 演示
level = '啦啦啦!!!'
}
return cfg_array_example3

+ 58
- 0
server/cfg_object.erl View File

@ -0,0 +1,58 @@
%% Automatic generation from -->>
%% excel file name : A_object表示例--cfg_object
%% excel sheet name : (sheet就不会附加到导出名后部分)
-module(cfg_object).
-compile(export_all).
%%
get('open_level') ->
90;
%% 1
get('add_value1') ->
100.1;
%% 2
get('add_value2') ->
100;
%% id
get('act_id') ->
1001;
%%
get('open') ->
"18:00:0";
%%
get(10000) ->
"前面字段为errorID,这里是错误描述,是的object配置的server,client字段名还支持数字作为key(但是转出格式为xml和jsonarray时就不支持了)";
%% 1
get('award1') ->
[[1001, 20], {1002, 20}, [1003, 30]];
%% 2
get('award2') ->
{{1001, 10}, [1002, 20]};
%% 3(xml是就会报错
get('award3') ->
#{1 => #{'res' => 1001, 'id' => 10001, 'count' => 1}, 2 => #{'res' => [1002, 1], 'id' => 10001, 'count' => 1}};
%% 4
get('award4') ->
#{'rr' => [1001, 20], 'ff' => [3006, 99], 'aa' => [7003, 1], 'test' => "这就是一个测试"};
%% 5
get('award5') ->
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9];
%%
get('award6') ->
[[1001, 20], [3006, 99], [7003, 1], #{'jsonobject' => [12356, 654321]}];
get(_) ->
undefined.

+ 71
- 0
server/cfg_object.ex View File

@ -0,0 +1,71 @@
## Automatic generation from -->>
## excel file name: A_object表示例--cfg_object
## excel sheet name: 武器(这个sheet就不会附加到导出名后部分)
defmodule Cfg_Object do
## 开放等级
def get(:open_level) do
90
end
## 额外添加属性值1
def get(:add_value1) do
100.1
end
## 额外添加属性值2
def get(:add_value2) do
100
end
## 活动id
def get(:act_id) do
1001
end
## 开始时间
def get(:open) do
"18:00:0"
end
## 错误信息
def get(10000) do
"前面字段为errorID,这里是错误描述,是的object配置的server,client字段名还支持数字作为key(但是转出格式为xml和jsonarray时就不支持了)"
end
## 奖励1
def get(:award1) do
[[1001, 20], {1002, 20}, [1003, 30]]
end
## 奖励2
def get(:award2) do
{{1001, 10}, [1002, 20]}
end
## 奖励3(这条转成xml是就会报错,因为KEY为数字)
def get(:award3) do
%{1 => %{:res => 1001, :id => 10001, :count => 1}, 2 => %{:res => [1002, 1], :id => 10001, :count => 1}}
end
## 奖励4
def get(:award4) do
%{:rr => [1001, 20], :ff => [3006, 99], :aa => [7003, 1], :test => "这就是一个测试"}
end
## 奖励5
def get(:award5) do
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
end
## 奖励
def get(:award6) do
[[1001, 20], [3006, 99], [7003, 1], %{:jsonobject => [12356, 654321]}]
end
def get(_) do
:undefined
end
end

+ 102
- 0
server/cfg_object.json View File

@ -0,0 +1,102 @@
{
"open_level":90,
"add_value1":100.1,
"add_value2":100,
"act_id":1001,
"open":"18:00:0",
"10000":"前面字段为errorID,这里是错误描述,是的object配置的server,client字段名还支持数字作为key(但是转出格式为xml和jsonarray时就不支持了)",
"award1":[
[
1001,
20
],
[
1002,
20
],
[
1003,
30
]
],
"award2":[
[
1001,
10
],
[
1002,
20
]
],
"award3":{
"1":{
"res":1001,
"id":10001,
"count":1
},
"2":{
"id":10001,
"count":1,
"res":[
1002,
1
]
}
},
"award4":{
"test":"这就是一个测试",
"rr":[
1001,
20
],
"ff":[
3006,
99
],
"aa":[
7003,
1
]
},
"award5":[
1,
2,
3,
4,
5,
6,
7,
8,
9,
9,
9,
9,
9,
9,
9,
9,
9,
9
],
"award6":[
[
1001,
20
],
[
3006,
99
],
[
7003,
1
],
{
"jsonobject":[
12356,
654321
]
}
]
}

+ 153
- 0
server/cfg_object.lua View File

@ -0,0 +1,153 @@
-- Automatic generation from -->>
-- excel file name: A_object表示例--cfg_object
-- excel sheet name: 武器(这个sheet就不会附加到导出名后部分)
local cfg_object =
{
-- 开放等级
open_level =90,
-- 额外添加属性值1
add_value1 =100.1,
-- 额外添加属性值2
add_value2 =100,
-- 活动id
act_id =1001,
-- 开始时间
open ='18:00:0',
-- 错误信息
[10000] ='前面字段为errorID,这里是错误描述,是的object配置的server,client字段名还支持数字作为key(但是转出格式为xml和jsonarray时就不支持了)',
-- 奖励1
award1 =
{
[1] =
{
[1] = 1001,
[2] = 20
},
[2] =
{
[1] = 1002,
[2] = 20
},
[3] =
{
[1] = 1003,
[2] = 30
}
},
-- 奖励2
award2 =
{
[1] =
{
[1] = 1001,
[2] = 10
},
[2] =
{
[1] = 1002,
[2] = 20
}
},
-- 奖励3(这条转成xml是就会报错)
award3 =
{
[1] =
{
res = 1001,
id = 10001,
count = 1
},
[2] =
{
id = 10001,
count = 1,
res =
{
[1] = 1002,
[2] = 1
}
}
},
-- 奖励4
award4 =
{
test = '这就是一个测试',
rr =
{
[1] = 1001,
[2] = 20
},
ff =
{
[1] = 3006,
[2] = 99
},
aa =
{
[1] = 7003,
[2] = 1
}
},
-- 奖励5
award5 =
{
[1] = 1,
[2] = 2,
[3] = 3,
[4] = 4,
[5] = 5,
[6] = 6,
[7] = 7,
[8] = 8,
[9] = 9,
[10] = 9,
[11] = 9,
[12] = 9,
[13] = 9,
[14] = 9,
[15] = 9,
[16] = 9,
[17] = 9,
[18] = 9
},
-- 奖励
award6 =
{
[1] =
{
[1] = 1001,
[2] = 20
},
[2] =
{
[1] = 3006,
[2] = 99
},
[3] =
{
[1] = 7003,
[2] = 1
},
[4] =
{
jsonobject =
{
[1] = 12356,
[2] = 654321
}
}
}
}
return cfg_object

+ 71
- 0
server/cfg_object1_cfg_object.ex View File

@ -0,0 +1,71 @@
## Automatic generation from -->>
## excel file name: A_object表示例--cfg_object1
## excel sheet name: A_object表示例--cfg_object
defmodule Cfg_Object1_Cfg_Object do
## 开放等级
def get(:open_level) do
90
end
## 额外添加属性值1
def get(:add_value1) do
100.1
end
## 额外添加属性值2
def get(:add_value2) do
100
end
## 活动id
def get(:act_id) do
1001
end
## 开始时间
def get(:open) do
"fgfdg"
end
## 错误信息
def get(10000) do
"前面字段为errorID,这里是错误描述,是的object配置的server,client字段名还支持数字作为key(但是转出格式为xml和jsonarray时就不支持了)"
end
## 奖励1
def get(:award1) do
[[1001, 20], {1002, 20}, [1003, 30]]
end
## 奖励2
def get(:award2) do
{{1001, 10}, [1002, 20]}
end
## 奖励3(这条转成xml是就会报错,因为KEY为数字)
def get(:award3) do
%{1 => %{:res => 1001, :id => 10001, :count => 1}, 2 => %{:res => [1002, 1], :id => 10001, :count => 1}}
end
## 奖励4
def get(:award4) do
%{:rr => [1001, 20], :ff => [3006, 99], :aa => [7003, 1], :test => "这就是一个测试"}
end
## 奖励5
def get(:award5) do
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
end
## 奖励
def get(:award6) do
[[1001, 20], [3006, 99], [7003, 1], %{:jsonobject => [12356, 654321]}]
end
def get(_) do
:undefined
end
end

+ 4
- 0
slpp/.gitignore View File

@ -0,0 +1,4 @@
*.pyc
*~

+ 19
- 0
slpp/LICENSE View File

@ -0,0 +1,19 @@
Copyright (c) 2010, 2011, 2012 SirAnthony <anthony at adsorbtion.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

+ 41
- 0
slpp/README.markdown View File

@ -0,0 +1,41 @@
#### SLPP
SLPP is a simple lua-python data structures parser.
Lua data check:
```lua
data = '{ array = { 65, 23, 5 }, dict = { string = "value", array = { 3, 6, 4}, mixed = { 43, 54.3, false, string = "value", 9 } } }'
> data = assert(loadstring('return ' .. data))()
> for i,j in pairs(data['dict']) do print(i,j) end
mixed table: 0x2014290
string value
array table: 0x2014200
```
Parse lua data:
```python
>>> from slpp import slpp as lua
>>> data = lua.decode('{ array = { 65, 23, 5 }, dict = { string = "value", array = { 3, 6, 4}, mixed = { 43, 54.3, false, string = "value", 9 } } }')
>>> print data
{'array': [65, 23, 5], 'dict': {'mixed': {0: 43, 1: 54.33, 2: False, 4: 9, 'string': 'value'}, 'array': [3, 6, 4], 'string': 'value'}}
```
Dump python object:
```python
>>> lua.encode(data)
'{array = {65,23,5},dict = {mixed = {43,54.33,false,9,string = "value"},array = {3,6,4},string = "value"}}'
```
Dump test:
```lua
> data = assert(loadstring('return ' .. '{array = {65,23,5,},dict = {mixed = {43,54.33,false,9,string = "value",},array = {3,6,4,},string = "value",},}'))()
> print(data['dict'])
table: 0x1b64ea0
> for i,j in pairs(data['dict']) do print(i,j) end
mixed table: 0x880afe0
array table: 0x880af60
string value
```

+ 0
- 0
slpp/__init__.py View File


+ 13
- 0
slpp/setup.py View File

@ -0,0 +1,13 @@
#!/usr/bin/env python
from distutils.core import setup
setup(
name='SLPP',
description='SLPP is a simple lua-python data structures parser',
version='1.0',
author='SirAnthony',
url='https://github.com/SirAnthony/slpp',
license='https://github.com/SirAnthony/slpp/blob/master/LICENSE',
keywords=['lua'],
py_modules=['slpp'],
)

BIN
slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229.zip View File


+ 4
- 0
slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/.gitignore View File

@ -0,0 +1,4 @@
*.pyc
*~

+ 19
- 0
slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/LICENSE View File

@ -0,0 +1,19 @@
Copyright (c) 2010, 2011, 2012 SirAnthony <anthony at adsorbtion.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

+ 41
- 0
slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/README.markdown View File

@ -0,0 +1,41 @@
#### SLPP
SLPP is a simple lua-python data structures parser.
Lua data check:
```lua
data = '{ array = { 65, 23, 5 }, dict = { string = "value", array = { 3, 6, 4}, mixed = { 43, 54.3, false, string = "value", 9 } } }'
> data = assert(loadstring('return ' .. data))()
> for i,j in pairs(data['dict']) do print(i,j) end
mixed table: 0x2014290
string value
array table: 0x2014200
```
Parse lua data:
```python
>>> from slpp import slpp as lua
>>> data = lua.decode('{ array = { 65, 23, 5 }, dict = { string = "value", array = { 3, 6, 4}, mixed = { 43, 54.3, false, string = "value", 9 } } }')
>>> print data
{'array': [65, 23, 5], 'dict': {'mixed': {0: 43, 1: 54.33, 2: False, 4: 9, 'string': 'value'}, 'array': [3, 6, 4], 'string': 'value'}}
```
Dump python object:
```python
>>> lua.encode(data)
'{array = {65,23,5},dict = {mixed = {43,54.33,false,9,string = "value"},array = {3,6,4},string = "value"}}'
```
Dump test:
```lua
> data = assert(loadstring('return ' .. '{array = {65,23,5,},dict = {mixed = {43,54.33,false,9,string = "value",},array = {3,6,4,},string = "value",},}'))()
> print(data['dict'])
table: 0x1b64ea0
> for i,j in pairs(data['dict']) do print(i,j) end
mixed table: 0x880afe0
array table: 0x880af60
string value
```

+ 0
- 0
slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/__init__.py View File


+ 13
- 0
slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/setup.py View File

@ -0,0 +1,13 @@
#!/usr/bin/env python
from distutils.core import setup
setup(
name='SLPP',
description='SLPP is a simple lua-python data structures parser',
version='1.0',
author='SirAnthony',
url='https://github.com/SirAnthony/slpp',
license='https://github.com/SirAnthony/slpp/blob/master/LICENSE',
keywords=['lua'],
py_modules=['slpp'],
)

+ 262
- 0
slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/slpp.py View File

@ -0,0 +1,262 @@
import re
import sys
ERRORS = {
'unexp_end_string': u'Unexpected end of string while parsing Lua string.',
'unexp_end_table': u'Unexpected end of table while parsing Lua string.',
'mfnumber_minus': u'Malformed number (no digits after initial minus).',
'mfnumber_dec_point': u'Malformed number (no digits after decimal point).',
'mfnumber_sci': u'Malformed number (bad scientific format).',
}
# Python 3 renamed the unicode type to str,
# the old str type has been replaced by bytes
try:
basestring
except NameError:
basestring = str
try:
unicode
except NameError:
unicode = str
class ParseError(Exception):
pass
class SLPP(object):
def __init__(self):
self.text = ''
self.ch = ''
self.at = 0
self.len = 0
self.depth = 0
self.space = re.compile('\s', re.M)
self.alnum = re.compile('\w', re.M)
self.newline = '\n'
self.tab = '\t'
def decode(self, text):
if not text or not isinstance(text, basestring):
return
#FIXME: only short comments removed
reg = re.compile('--.*$', re.M)
text = reg.sub('', text, 0)
self.text = text
self.at, self.ch, self.depth = 0, '', 0
self.len = len(text)
self.next_chr()
result = self.value()
return result
def encode(self, obj):
self.depth = 0
return self.__encode(obj)
def __encode(self, obj):
s = ''
tab = self.tab
newline = self.newline
tp = type(obj)
if isinstance(obj, str):
s += '"%s"' % obj.replace(r'"', r'\"')
if isinstance(obj, unicode):
s += '"%s"' % obj.encode('utf-8').replace(r'"', r'\"')
elif tp in [int, float, long, complex]:
s += str(obj)
elif tp is bool:
s += str(obj).lower()
elif obj is None:
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) ):
newline = tab = ''
dp = tab * self.depth
s += "%s{%s" % (tab * (self.depth - 2), newline)
if tp is dict:
contents = []
for k, v in obj.iteritems():
if type(k) is int:
contents.append(self.__encode(v))
else:
contents.append(dp + '%s = %s' % (k, self.__encode(v)))
s += (',%s' % newline).join(contents)
else:
s += (',%s' % newline).join(
[dp + self.__encode(el) for el in obj])
self.depth -= 1
s += "%s%s}" % (newline, tab * self.depth)
return s
def white(self):
while self.ch:
if self.space.match(self.ch):
self.next_chr()
else:
break
def next_chr(self):
if self.at >= self.len:
self.ch = None
return None
self.ch = self.text[self.at]
self.at += 1
return True
def value(self):
self.white()
if not self.ch:
return
if self.ch == '{':
return self.object()
if self.ch == "[":
self.next_chr()
if self.ch in ['"', "'", '[']:
return self.string(self.ch)
if self.ch.isdigit() or self.ch == '-':
return self.number()
return self.word()
def string(self, end=None):
s = ''
start = self.ch
if end == '[':
end = ']'
if start in ['"', "'", '[']:
while self.next_chr():
if self.ch == end:
self.next_chr()
if start != "[" or self.ch == ']':
return s
if self.ch == '\\' and start == end:
self.next_chr()
if self.ch != end:
s += '\\'
s += self.ch
raise Exception(ERRORS['unexp_end_string'])
def object(self):
o = {}
k = None
idx = 0
numeric_keys = False
self.depth += 1
self.next_chr()
self.white()
if self.ch and self.ch == '}':
self.depth -= 1
self.next_chr()
return o #Exit here
else:
while self.ch:
self.white()
if self.ch == '{':
o[idx] = self.object()
idx += 1
continue
elif self.ch == '}':
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:
ar = []
for key in o:
ar.insert(key, o[key])
o = ar
return o #or here
else:
if self.ch == ',':
self.next_chr()
continue
else:
k = self.value()
if self.ch == ']':
numeric_keys = True
self.next_chr()
self.white()
ch = self.ch
if ch in ('=', ','):
self.next_chr()
self.white()
if ch == '=':
o[k] = self.value()
else:
o[idx] = k
idx += 1
k = None
raise Exception(ERRORS['unexp_end_table']) #Bad exit here
words = {'true': True, 'false': False, 'nil': None}
def word(self):
s = ''
if self.ch != '\n':
s = self.ch
self.next_chr()
while self.ch is not None and self.alnum.match(self.ch) and s not in self.words:
s += self.ch
self.next_chr()
return self.words.get(s, s)
def number(self):
def next_digit(err):
n = self.ch
self.next_chr()
if not self.ch or not self.ch.isdigit():
raise ParseError(err)
return n
n = ''
try:
if self.ch == '-':
n += next_digit(ERRORS['mfnumber_minus'])
n += self.digit()
if n == '0' and self.ch in ['x', 'X']:
n += self.ch
self.next_chr()
n += self.hex()
else:
if self.ch and self.ch == '.':
n += next_digit(ERRORS['mfnumber_dec_point'])
n += self.digit()
if self.ch and self.ch in ['e', 'E']:
n += self.ch
self.next_chr()
if not self.ch or self.ch not in ('+', '-'):
raise ParseError(ERRORS['mfnumber_sci'])
n += next_digit(ERRORS['mfnumber_sci'])
n += self.digit()
except ParseError:
t, e = sys.exc_info()[:2]
print(e)
return 0
try:
return int(n, 0)
except:
pass
return float(n)
def digit(self):
n = ''
while self.ch and self.ch.isdigit():
n += self.ch
self.next_chr()
return n
def hex(self):
n = ''
while self.ch and \
(self.ch in 'ABCDEFabcdef' or self.ch.isdigit()):
n += self.ch
self.next_chr()
return n
slpp = SLPP()
__all__ = ['slpp']

+ 182
- 0
slpp/slpp-c4d7f69af338f973c0ef21a9a06a145936367229/tests.py View File

@ -0,0 +1,182 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from slpp import slpp as lua
"""
Tests for slpp
"""
def is_iterator(obj):
"""
>>> assert is_iterator(list()) is True
>>> assert is_iterator(int) is False
"""
if isinstance(obj, (list, tuple)):
return True
try:
iter(obj)
return True
except TypeError:
return False
def differ(value, origin):
"""
Same:
>>> differ(1, 1)
>>> differ([2, 3], [2, 3])
>>> differ({'1': 3, '4': '6'}, {'4': '6', '1': 3})
>>> differ('4', '4')
Different:
>>> differ(1, 2)
Traceback (most recent call last):
...
AssertionError: 1 not match original: 2.
>>> differ([2, 3], [3, 2])
Traceback (most recent call last):
...
AssertionError: 2 not match original: 3.
>>> differ({'6': 4, '3': '1'}, {'4': '6', '1': 3})
Traceback (most recent call last):
...
AssertionError: {'3': '1', '6': 4} not match original: {'1': 3, '4': '6'};
Key: 1, item: 3
>>> differ('4', 'no')
Traceback (most recent call last):
...
AssertionError: 4 not match original: no.
"""
if type(value) is not type(origin):
raise AssertionError('Types does not match: {0}, {1}'.format(type(value), type(origin)))
if isinstance(origin, dict):
for key, item in origin.items():
try:
differ(value[key], item)
except KeyError:
raise AssertionError('''{0} not match original: {1};
Key: {2}, item: {3}'''.format(value, origin, key, item))
return
if isinstance(origin, basestring):
assert value == origin, '{0} not match original: {1}.'.format(value, origin)
return
if is_iterator(origin):
for i in range(0, len(origin)):
try:
differ(value[i], origin[i])
except IndexError:
raise AssertionError(
'{0} not match original: {1}. Item {2} not found'.format(
response, origin, origin[i]))
except Exception, e:
raise e
return
assert value == origin, '{0} not match original: {1}.'.format(value, origin)
def number_test():
"""
Integer and float:
>>> assert lua.decode('3') == 3
>>> assert lua.decode('4.1') == 4.1
Negative float:
>>> assert lua.decode('-0.45') == -0.45
Scientific:
>>> assert lua.decode('3e-7') == 3e-7
>>> assert lua.decode('-3.23e+17') == -3.23e+17
Hex:
>>> assert lua.decode('0x3a') == 0x3a
#4
>>> differ(lua.decode('''{ \
ID = 0x74fa4cae, \
Version = 0x07c2, \
Manufacturer = 0x21544948 \
}'''), { \
'ID': 0x74fa4cae, \
'Version': 0x07c2, \
'Manufacturer': 0x21544948 \
})
"""
pass
def test_bool():
"""
>>> assert lua.decode('false') == False
>>> assert lua.decode('true') == True
>>> assert lua.encode(False) == 'false'
>>> assert lua.encode(True) == 'true'
"""
pass
def test_nil():
"""
>>> assert lua.decode('nil') == None
>>> assert lua.encode(None) == 'nil'
"""
pass
def table_test():
"""
Bracketed string key:
>>> assert lua.decode('{[10] = 1}') == {10: 1}
Void table:
>>> assert lua.decode('{nil}') == []
Values-only table:
>>> assert lua.decode('{"10"}') == ["10"]
Last zero
>>> assert lua.decode('{0, 1, 0}') == [0,1,0]
"""
pass
def string_test():
r"""
Escape test:
>>> assert lua.decode(r"'test\'s string'") == "test's string"
Add escaping on encode:
>>> assert lua.encode({'a': 'func("call()");'}) == '{\n\ta = "func(\\"call()\\");"\n}'
"""
pass
def basic_test():
"""
No data loss:
>>> data = '{ array = { 65, 23, 5 }, dict = { string = "value", array = { 3, 6, 4}, mixed = { 43, 54.3, false, string = "value", 9 } } }'
>>> d = lua.decode(data)
>>> differ(d, lua.decode(lua.encode(d)))
"""
pass
def unicode_test():
ur"""
>>> assert lua.encode(u'Привет') == '"\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82"'
>>> assert lua.encode({'s': u'Привет'}) == '{\n\ts = "Привет"\n}'
"""
pass
if __name__ == '__main__':
import doctest
doctest.testmod()

+ 262
- 0
slpp/slpp.py View File

@ -0,0 +1,262 @@
import re
import sys
ERRORS = {
'unexp_end_string': u'Unexpected end of string while parsing Lua string.',
'unexp_end_table': u'Unexpected end of table while parsing Lua string.',
'mfnumber_minus': u'Malformed number (no digits after initial minus).',
'mfnumber_dec_point': u'Malformed number (no digits after decimal point).',
'mfnumber_sci': u'Malformed number (bad scientific format).',
}
# Python 3 renamed the unicode type to str,
# the old str type has been replaced by bytes
try:
basestring
except NameError:
basestring = str
try:
unicode
except NameError:
unicode = str
class ParseError(Exception):
pass
class SLPP(object):
def __init__(self):
self.text = ''
self.ch = ''
self.at = 0
self.len = 0
self.depth = 0
self.space = re.compile('\s', re.M)
self.alnum = re.compile('\w', re.M)
self.newline = '\n'
self.tab = '\t'
def decode(self, text):
if not text or not isinstance(text, basestring):
return
#FIXME: only short comments removed
reg = re.compile('--.*$', re.M)
text = reg.sub('', text, 0)
self.text = text
self.at, self.ch, self.depth = 0, '', 0
self.len = len(text)
self.next_chr()
result = self.value()
return result
def encode(self, obj):
self.depth = 0
return self.__encode(obj)
def __encode(self, obj):
s = ''
tab = self.tab
newline = self.newline
tp = type(obj)
if isinstance(obj, str):
s += '"%s"' % obj.replace(r'"', r'\"')
if isinstance(obj, unicode):
s += '"%s"' % obj.encode('utf-8').replace(r'"', r'\"')
elif tp in [int, float, long, complex]:
s += str(obj)
elif tp is bool:
s += str(obj).lower()
elif obj is None:
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) ):
newline = tab = ''
dp = tab * self.depth
s += "%s{%s" % (tab * (self.depth - 2), newline)
if tp is dict:
contents = []
for k, v in obj.iteritems():
if type(k) is int:
contents.append(self.__encode(v))
else:
contents.append(dp + '%s = %s' % (k, self.__encode(v)))
s += (',%s' % newline).join(contents)
else:
s += (',%s' % newline).join(
[dp + self.__encode(el) for el in obj])
self.depth -= 1
s += "%s%s}" % (newline, tab * self.depth)
return s
def white(self):
while self.ch:
if self.space.match(self.ch):
self.next_chr()
else:
break
def next_chr(self):
if self.at >= self.len:
self.ch = None
return None
self.ch = self.text[self.at]
self.at += 1
return True
def value(self):
self.white()
if not self.ch:
return
if self.ch == '{':
return self.object()
if self.ch == "[":
self.next_chr()
if self.ch in ['"', "'", '[']:
return self.string(self.ch)
if self.ch.isdigit() or self.ch == '-':
return self.number()
return self.word()
def string(self, end=None):
s = ''
start = self.ch
if end == '[':
end = ']'
if start in ['"', "'", '[']:
while self.next_chr():
if self.ch == end:
self.next_chr()
if start != "[" or self.ch == ']':
return s
if self.ch == '\\' and start == end:
self.next_chr()
if self.ch != end:
s += '\\'
s += self.ch
raise Exception(ERRORS['unexp_end_string'])
def object(self):
o = {}
k = None
idx = 0
numeric_keys = False
self.depth += 1
self.next_chr()
self.white()
if self.ch and self.ch == '}':
self.depth -= 1
self.next_chr()
return o #Exit here
else:
while self.ch:
self.white()
if self.ch == '{':
o[idx] = self.object()
idx += 1
continue
elif self.ch == '}':
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:
ar = []
for key in o:
ar.insert(key, o[key])
o = ar
return o #or here
else:
if self.ch == ',':
self.next_chr()
continue
else:
k = self.value()
if self.ch == ']':
numeric_keys = True
self.next_chr()
self.white()
ch = self.ch
if ch in ('=', ','):
self.next_chr()
self.white()
if ch == '=':
o[k] = self.value()
else:
o[idx] = k
idx += 1
k = None
raise Exception(ERRORS['unexp_end_table']) #Bad exit here
words = {'true': True, 'false': False, 'nil': None}
def word(self):
s = ''
if self.ch != '\n':
s = self.ch
self.next_chr()
while self.ch is not None and self.alnum.match(self.ch) and s not in self.words:
s += self.ch
self.next_chr()
return self.words.get(s, s)
def number(self):
def next_digit(err):
n = self.ch
self.next_chr()
if not self.ch or not self.ch.isdigit():
raise ParseError(err)
return n
n = ''
try:
if self.ch == '-':
n += next_digit(ERRORS['mfnumber_minus'])
n += self.digit()
if n == '0' and self.ch in ['x', 'X']:
n += self.ch
self.next_chr()
n += self.hex()
else:
if self.ch and self.ch == '.':
n += next_digit(ERRORS['mfnumber_dec_point'])
n += self.digit()
if self.ch and self.ch in ['e', 'E']:
n += self.ch
self.next_chr()
if not self.ch or self.ch not in ('+', '-'):
raise ParseError(ERRORS['mfnumber_sci'])
n += next_digit(ERRORS['mfnumber_sci'])
n += self.digit()
except ParseError:
t, e = sys.exc_info()[:2]
print(e)
return 0
try:
return int(n, 0)
except:
pass
return float(n)
def digit(self):
n = ''
while self.ch and self.ch.isdigit():
n += self.ch
self.next_chr()
return n
def hex(self):
n = ''
while self.ch and \
(self.ch in 'ABCDEFabcdef' or self.ch.isdigit()):
n += self.ch
self.next_chr()
return n
slpp = SLPP()
__all__ = ['slpp']

+ 182
- 0
slpp/tests.py View File

@ -0,0 +1,182 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from slpp import slpp as lua
"""
Tests for slpp
"""
def is_iterator(obj):
"""
>>> assert is_iterator(list()) is True
>>> assert is_iterator(int) is False
"""
if isinstance(obj, (list, tuple)):
return True
try:
iter(obj)
return True
except TypeError:
return False
def differ(value, origin):
"""
Same:
>>> differ(1, 1)
>>> differ([2, 3], [2, 3])
>>> differ({'1': 3, '4': '6'}, {'4': '6', '1': 3})
>>> differ('4', '4')
Different:
>>> differ(1, 2)
Traceback (most recent call last):
...
AssertionError: 1 not match original: 2.
>>> differ([2, 3], [3, 2])
Traceback (most recent call last):
...
AssertionError: 2 not match original: 3.
>>> differ({'6': 4, '3': '1'}, {'4': '6', '1': 3})
Traceback (most recent call last):
...
AssertionError: {'3': '1', '6': 4} not match original: {'1': 3, '4': '6'};
Key: 1, item: 3
>>> differ('4', 'no')
Traceback (most recent call last):
...
AssertionError: 4 not match original: no.
"""
if type(value) is not type(origin):
raise AssertionError('Types does not match: {0}, {1}'.format(type(value), type(origin)))
if isinstance(origin, dict):
for key, item in origin.items():
try:
differ(value[key], item)
except KeyError:
raise AssertionError('''{0} not match original: {1};
Key: {2}, item: {3}'''.format(value, origin, key, item))
return
if isinstance(origin, basestring):
assert value == origin, '{0} not match original: {1}.'.format(value, origin)
return
if is_iterator(origin):
for i in range(0, len(origin)):
try:
differ(value[i], origin[i])
except IndexError:
raise AssertionError(
'{0} not match original: {1}. Item {2} not found'.format(
response, origin, origin[i]))
except Exception, e:
raise e
return
assert value == origin, '{0} not match original: {1}.'.format(value, origin)
def number_test():
"""
Integer and float:
>>> assert lua.decode('3') == 3
>>> assert lua.decode('4.1') == 4.1
Negative float:
>>> assert lua.decode('-0.45') == -0.45
Scientific:
>>> assert lua.decode('3e-7') == 3e-7
>>> assert lua.decode('-3.23e+17') == -3.23e+17
Hex:
>>> assert lua.decode('0x3a') == 0x3a
#4
>>> differ(lua.decode('''{ \
ID = 0x74fa4cae, \
Version = 0x07c2, \
Manufacturer = 0x21544948 \
}'''), { \
'ID': 0x74fa4cae, \
'Version': 0x07c2, \
'Manufacturer': 0x21544948 \
})
"""
pass
def test_bool():
"""
>>> assert lua.decode('false') == False
>>> assert lua.decode('true') == True
>>> assert lua.encode(False) == 'false'
>>> assert lua.encode(True) == 'true'
"""
pass
def test_nil():
"""
>>> assert lua.decode('nil') == None
>>> assert lua.encode(None) == 'nil'
"""
pass
def table_test():
"""
Bracketed string key:
>>> assert lua.decode('{[10] = 1}') == {10: 1}
Void table:
>>> assert lua.decode('{nil}') == []
Values-only table:
>>> assert lua.decode('{"10"}') == ["10"]
Last zero
>>> assert lua.decode('{0, 1, 0}') == [0,1,0]
"""
pass
def string_test():
r"""
Escape test:
>>> assert lua.decode(r"'test\'s string'") == "test's string"
Add escaping on encode:
>>> assert lua.encode({'a': 'func("call()");'}) == '{\n\ta = "func(\\"call()\\");"\n}'
"""
pass
def basic_test():
"""
No data loss:
>>> data = '{ array = { 65, 23, 5 }, dict = { string = "value", array = { 3, 6, 4}, mixed = { 43, 54.3, false, string = "value", 9 } } }'
>>> d = lua.decode(data)
>>> differ(d, lua.decode(lua.encode(d)))
"""
pass
def unicode_test():
ur"""
>>> assert lua.encode(u'Привет') == '"\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82"'
>>> assert lua.encode({'s': u'Привет'}) == '{\n\ts = "Привет"\n}'
"""
pass
if __name__ == '__main__':
import doctest
doctest.testmod()

+ 56
- 0
writer.py View File

@ -0,0 +1,56 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
import json
from xml.dom.minidom import Document
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
BASE_LENGTH = 60
BASE_INDENT = " "
INDENT_LIST = {}
class Writer(object):
def __init__(self,doc_name,sheet_name, base_name, keys_list, comment_text):
# 文件名包含中文则需要转unicode
#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
# 文件后缀
def suffix(self):
pass
# 文件内容
def context(self,ctx):
pass
# 注释开始
def comment_start(self):
pass
# 注释结束
def comment_end(self):
pass
# 文件注释(千万不要加时间,影响svn)
def comment(self):
comment = []
return "".join( comment )

+ 319
- 0
writer_elixir.py View File

@ -0,0 +1,319 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
from writer import *
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
BASE_LENGTH = 60
BASE_INDENT = " "
INDENT_LIST = {}
class ElixirWriter(Writer):
# 文件后缀
def suffix(self):
return ".ex"
def comment(self):
comment = [
'## Automatic generation from -->>'
'\n## excel file name: ' + self.doc_name +
'\n## excel sheet name: ' + self.sheet_name,
'\ndefmodule ' + self.base_name.title() + ' do\n\n'
]
return "\n".join( comment )
# 获取缩进字符串
def indent_ctx( self,indent ):
if indent <= 0: return ""
if indent not in INDENT_LIST:
INDENT_LIST[indent] = ""
else:
ctx = BASE_INDENT*indent
INDENT_LIST[indent] = ctx
return INDENT_LIST[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 )
comment = self.comment_text[k]
val_type = type( lk )
if str == val_type :
if lk.replace(".", "").isdigit() :
lk.replace("\"", "")
else :
lk = ':' + lk.replace("\"", "")
key = "".join( [" def get(",lk,") do\n"] )
val = "".join( [" ## ", comment, "\n", key, " ", lv, "\n end\n\n"] )
dict_text_list.append( val )
dict_str = "".join( dict_text_list )
dict_str = dict_str + " def get(_) do\n :undefined\n end\n\nend"
return False, dict_str
def list_to_text(self, value, indent):
list_text_list = []
# 先定义 struct
struct_text_list = []
struct_len = len(self.comment_text)
tem_count = 0
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() :
lk.replace("\"", "")
else :
lk = ':' + lk.replace("\"", "")
if tem_count != struct_len :
lk = lk + ','
else :
lk = lk
if None == comment :
comment = ""
val = "".join( [lk.ljust(20, " "), "\t## ", comment, "\n"] )
struct_text_list.append( val )
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 ) :
# 生成对应的 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 )
key_list.append(lv)
all_key_list.append(key_list)
tem = ", ".join( key_list )
key = "".join( [" def get(",tem,") do\n %", self.base_name.title(), "{\n "] )
# 生成对应的value
value_list = []
onedict_len = len(onedict)
tem_count = 0
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 )
val_type = type( lk )
if str == val_type :
if lk.replace(".", "").isdigit() :
lk.replace("\"", "")
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 )
value_list_str = " ".join(value_list)
end_str = "".join( [key, value_list_str, " }\n end\n\n"] )
list_text_list.append( end_str )
underline_list = []
for i in self.keys_list :
underline_list.append('_')
end_str = ", ".join(underline_list)
no_match_str = " def get(" + end_str + ") do\n :undefined\n end\n\n"
list_text_list.append(no_match_str)
# 生成 get_all() 函数
get_all_fun = []
allkey_len = len(all_key_list)
tem_count = 0
for i, ival in enumerate(all_key_list) :
tem_count += 1
if tem_count != allkey_len :
oneval = '{' + ", ".join(ival) + '},\n'
get_all_fun.append(oneval)
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"] )
list_text_list.append( end_str )
# 生成 get_list() 函数
get_list_fun = []
keys_len = len(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 :
get_tem_dict = {}
underline_list = []
for i, ival in enumerate(all_key_list) :
key_tem_list = []
j = 0
underline_list = []
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) :
oldlist = get_tem_dict[keystr]
oldlist.append(ival)
get_tem_dict[keystr] = oldlist
else :
get_tem_dict[keystr] = [ival]
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) :
tem_count += 1
if tem_count != value_len :
oneval = '{' + ", ".join(lval) + '},\n'
value_tem_list.append(oneval)
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"] )
get_list_fun.append(end_str)
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 )
return False, dict_str
# 转换为文本数据 之前解析出来的excel数据存放方式存在LIST(array格式)和DICT(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)
# python的dict转换为elixir的map类型
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 )
val_type = type( lk )
if str == val_type :
if lk.replace(".", "").isdigit() :
lk.replace("\"", "")
else :
lk = ':' + lk.replace("\"", "")
key = "".join( [lk," => "] )
val = "".join( [key, lv] )
dict_ctx_list.append(val)
dict_str = ", ".join( dict_ctx_list )
return False,"".join( ["%{",dict_str,"}"] )
# python的list转换为elixir的list类型
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 )
list_str = ", ".join( list_ctx_list )
return False,"".join( ["[",list_str,"]"] )
# python的tuple转换为elixir的tuple类型
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 )
# 返回 {a,b,c}这种不换行的格式
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 :
# 1001.0 -->> 001 去除多余小数点
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] )

+ 259
- 0
writer_erlang_erl.py View File

@ -0,0 +1,259 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
from writer import *
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
BASE_LENGTH = 60
BASE_INDENT = " "
INDENT_LIST = {}
class ErlangerlWriter(Writer):
# 文件后缀
def suffix(self):
return ".erl"
def comment(self):
comment = [
'%% Automatic generation from -->>'
'\n%% excel file name : ' + self.doc_name +
'\n%% excel sheet name : ' + self.sheet_name,
'\n-module(' + self.base_name + ').',
'\n'
]
return "\n".join( comment )
# 获取缩进字符串
def indent_ctx( self,indent ):
if indent <= 0: return ""
if indent not in INDENT_LIST:
INDENT_LIST[indent] = ""
else:
ctx = BASE_INDENT*indent
INDENT_LIST[indent] = ctx
return INDENT_LIST[indent]
def dict_to_text(self, value, indent) :
dict_text_list = []
dict_text_list.append("-compile(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 )
comment = self.comment_text[k]
val_type = type( lk )
if str == val_type :
lk = lk.replace("\"", "\'")
key = "".join( ["get(",lk,") ->\n"] )
val = "".join( ["%% ", comment, "\n", key, " ", lv, ";\n\n"] )
dict_text_list.append( val )
dict_str = "".join( dict_text_list )
dict_str = dict_str + "get(_) ->\n undefined."
return False, dict_str
def list_to_text(self, value, indent):
list_text_list = []
val = "-include(\"" + self.base_name + ".hrl\").\n" + "-compile(export_all).\n\n"
list_text_list.append(val)
all_key_list = []
# 生成 get() 函数
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 )
key_list.append(lv)
all_key_list.append(key_list)
tem = ", ".join( key_list )
key = "".join( ["get(",tem,") ->\n #", self.base_name, "{\n "] )
# 生成对应的value
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 )
val_type = type( lk )
if str == val_type :
lk = lk.replace("\"", "\'")
oneval = "".join( [lk, " = ", lv , "\n"] )
value_list.append( oneval )
value_list_str = " ,".join(value_list)
end_str = "".join( [key, value_list_str, " };\n\n"] )
list_text_list.append( end_str )
underline_list = []
for i in self.keys_list :
underline_list.append('_')
end_str = ", ".join(underline_list)
no_match_str = "get(" + end_str + ") ->\n undefined.\n\n"
list_text_list.append(no_match_str)
# 生成 get_all() 函数
get_all_fun = []
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 = 'get_all() ->\n [\n '
end_str = "".join( [start_str, value_list_str, " ].\n\n"] )
list_text_list.append( end_str )
# 生成 get_list() 函数
get_list_fun = []
keys_len = len(self.keys_list)
for key in self.keys_list :
keyindex = self.keys_list[key]
if keyindex == 1 :
list_text_list.append( 'get_list() ->\n get_all().\n\n')
elif keyindex <= keys_len :
get_tem_dict = {}
underline_list = []
for i, ival in enumerate(all_key_list) :
key_tem_list = []
j = 0
underline_list = []
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) :
oldlist = get_tem_dict[keystr]
oldlist.append(ival)
get_tem_dict[keystr] = oldlist
else :
get_tem_dict[keystr] = [ival]
for onekey in get_tem_dict :
value_tem_list = []
valuelist = get_tem_dict[onekey]
for l, lval in enumerate(valuelist) :
oneval = '{' + ", ".join(lval) + '}\n'
value_tem_list.append(oneval)
start = 'get_list' + onekey + ' ->\n [\n '
val = "".join( [start, " ,".join(value_tem_list), " ];\n\n"] )
get_list_fun.append(val)
no_match_str = "".join('get_list(' + ", ".join(underline_list) + ') ->\n [].\n\n')
get_list_fun.append(no_match_str)
value_list = "".join(get_list_fun)
list_text_list.append( value_list )
dict_str = "".join( list_text_list )
return False, dict_str
# 转换为文本数据 之前解析出来的excel数据存放方式存在LIST(array格式)和DICT(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)
# python的dict转换为erlang的map类型
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 )
val_type = type( lk )
if str == val_type :
lk = lk.replace("\"", "\'")
key = "".join( [lk," => "] )
val = "".join( [key, lv] )
dict_ctx_list.append(val)
dict_str = ", ".join( dict_ctx_list )
return False,"".join( ["#{",dict_str,"}"] )
# python的list转换为erlang的list类型
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 )
list_str = ", ".join( list_ctx_list )
return False,"".join( ["[",list_str,"]"] )
# python的tuple转换为erlang的tuple类型
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 )
# 返回 {a,b,c}这种不换行的格式
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 :
# 1001.0 -->> 001 去除多余小数点
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 )
return "".join( [self.comment(),"",str_ctx] )

+ 152
- 0
writer_erlang_hrl.py View File

@ -0,0 +1,152 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
from writer import *
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
BASE_LENGTH = 60
BASE_INDENT = " "
INDENT_LIST = {}
class ErlanghrlWriter(Writer):
# 文件后缀
def suffix(self):
return ".hrl"
def comment(self):
comment = [
'%% 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 )
# 获取缩进字符串
def indent_ctx( self,indent ) :
if indent <= 0: return ""
if indent not in INDENT_LIST :
INDENT_LIST[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 :
comment = self.comment_text[k]
k_indent,lk = self.to_target_lang( k,indent )
val_type = type( lk )
if str == val_type :
lk = lk.replace("\"", "\'")
if None == comment :
comment = ""
val = "".join( [lk.ljust(20, " "), "\t%% ", comment, "\n"] )
list_text_list.append( val )
list_str = " ,".join( list_text_list )
list_str = list_str + " })."
return False, list_str
# 转换为文本数据 之前解析出来的excel数据存放方式存在LIST(array格式)和DICT(object格式)两种类型
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的dict转换为erlang的map类型
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 )
val_type = type( lk )
if str == val_type :
lk = lk.replace("\"", "\'")
key = "".join( [lk," => "] )
val = "".join( [key, lv] )
dict_ctx_list.append(val)
dict_str = ",".join( dict_ctx_list )
return False,"".join( ["#{",dict_str,"}"] )
# python的list转换为erlang的list类型
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 )
list_str = ",".join( list_ctx_list )
return False,"".join( ["[",list_str,"]"] )
# python的tuple转换为erlang的tuple类型
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 )
# 返回 {a,b,c}这种不换行的格式
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 :
# 1001.0 -->> 001 去除多余小数点
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 None

+ 41
- 0
writer_json_array.py View File

@ -0,0 +1,41 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
import json
from writer import *
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
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=(',', ':') )

+ 201
- 0
writer_json_object.py View File

@ -0,0 +1,201 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
from writer import *
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
BASE_LENGTH = 60
BASE_INDENT = " "
INDENT_LIST = {}
class JsonobjectWriter(Writer):
# 文件后缀
def suffix(self):
return ".json"
def comment(self):
comment = []
return "\n".join( comment )
# 获取缩进字符串
def indent_ctx( self,indent ):
if indent <= 0: return ""
if indent not in INDENT_LIST:
ctx = BASE_INDENT*indent
INDENT_LIST[indent] = ctx
return INDENT_LIST[indent]
def dict_to_text(self, value, indent) :
dict_ctx_list = []
is_indent,lv = self.to_target_lang( value, indent)
dict_ctx_list.append(lv)
dict_str = "".join( dict_ctx_list )
return False,"".join( [dict_str] )
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 :
lv = onedict[k]
if cur_key_index == total_key_cnt :
storge_dict[lv] = onedict
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] ={}
new_storge_dict = storge_dict[lv]
self.list_to_dit(cur_key_index + 1, total_key_cnt, onedict, new_storge_dict)
def list_to_text(self, value, indent):
list_text_list = []
## 处理多个key的情况
key_value_list = {}
key_cnt = len(self.keys_list)
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 )
list_text_list.append(list_str)
return False,"".join( list_text_list )
# 转换为文本数据 之前解析出来的excel数据存放方式存在LIST(array格式)和DICT(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)
# dict转换为json类型
def dict_to_json(self,value,indent):
dict_ctx_list = []
#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 ) :
lvalue = value[k]
lvalue_type = type(lvalue)
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 )
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 )
for k in ( value ) :
lvalue = value[k]
lvalue_type = type(lvalue)
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 :
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 )
dict_str = "".join(dict_ctx_list)
return True,"".join(["{\n" , dict_str, "\n",cur_indent,"}"] )
# list转换为json类型
def list_to_json(self,value,indent):
list_ctx_list = []
#if indent % 2 != 0 :
# indent += 1
cur_indent = self.indent_ctx(indent)
next_indent = self.indent_ctx(indent + 1)
index_cnt = 1
list_len = len(value)
tem_count = 0
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 )
index_cnt += 1
list_str = "".join(list_ctx_list)
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 :
# 1001.0 -->> 001 去除多余小数点
if int( value ) == value :
return False,str( int(value) )
return False, str( value )
elif str == val_type or unicode == val_type:
# 字符串要用单引号,因为Lua里单引号级别比双引号高
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] )

+ 273
- 0
writer_lua.py View File

@ -0,0 +1,273 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
from writer import *
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
BASE_LENGTH = 60
BASE_INDENT = " "
INDENT_LIST = {}
class LuaWriter(Writer):
# 文件后缀
def suffix(self):
return ".lua"
def comment(self):
comment = [
'-- Automatic generation from -->>'
'\n-- excel file name: ' + self.doc_name +
'\n-- excel sheet name: ' + self.sheet_name,
'\nlocal ' + self.base_name + ' =\n'
]
return "\n".join( comment )
# 获取缩进字符串
def indent_ctx( self,indent ):
if indent <= 0: return ""
if indent not in INDENT_LIST:
ctx = BASE_INDENT*indent
INDENT_LIST[indent] = ctx
return INDENT_LIST[indent]
def dict_to_text(self, value, indent) :
dict_ctx_list = []
cur_indent = self.indent_ctx(indent)
next_indent = self.indent_ctx(indent + 1)
tem_count = 0
total_len = len(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 )
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 :
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] )
dict_ctx_list.append( val )
dict_str = "".join( dict_ctx_list )
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 ) :
key_index = self.keys_list.get(k, None)
if None != key_index and key_index == cur_key_index :
lv = onedict[k]
if cur_key_index == total_key_cnt :
storge_dict[lv] = onedict
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] ={}
new_storge_dict = storge_dict[lv]
self.list_to_dit(cur_key_index + 1, total_key_cnt, onedict, new_storge_dict)
def list_to_text(self, value, indent):
list_text_list = []
# 先把各个字段的注释放在前面
comment_text_list = []
for k in self.comment_text :
comment = self.comment_text[k]
k_indent,lk = self.to_target_lang( k,indent )
lk = lk.replace("\'", "")
if None == comment :
comment = ""
val = "".join( [ '--: ', lk.ljust(20, " "), "\t## ", comment, "\n"] )
comment_text_list.append( val )
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 ) :
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 )
list_text_list.append(list_str)
return False,"".join( list_text_list )
# 转换为文本数据 之前解析出来的excel数据存放方式存在LIST(array格式)和DICT(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)
# dict转换为lua类型
def dict_to_lua(self,value,indent):
dict_ctx_list = []
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 ) :
lvalue = value[k]
lvalue_type = type(lvalue)
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 )
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 )
for k in ( value ) :
lvalue = value[k]
lvalue_type = type(lvalue)
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 :
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 )
dict_str = "".join(dict_ctx_list)
return True,"".join(['\n', cur_indent,"{\n" , dict_str, "\n",cur_indent,"}"] )
# list转换为lua类型
def list_to_lua(self,value,indent):
list_ctx_list = []
if indent % 2 != 0 :
indent += 1
cur_indent = self.indent_ctx(indent)
next_indent = self.indent_ctx(indent + 1)
index_cnt = 1
list_len = len(value)
tem_count = 0
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 )
index_cnt += 1
list_str = "".join(list_ctx_list)
return True,"".join(['\n', cur_indent,"{\n" , list_str, "\n",cur_indent,"}"] )
# tuple转换为lua类型
def tuple_to_lua(self,value1,indent):
value = list(value1)
list_ctx_list = []
if indent % 2 != 0 :
indent += 1
cur_indent = self.indent_ctx(indent)
next_indent = self.indent_ctx(indent + 1)
index_cnt = 1
list_len = len(value)
tem_count = 0
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 )
index_cnt += 1
list_str = "".join(list_ctx_list)
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 :
# 1001.0 -->> 001 去除多余小数点
if int( value ) == value :
return False,str( int(value) )
return False,str( value )
elif str == val_type or unicode == val_type:
# 字符串要用单引号,因为Lua里单引号级别比双引号高
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] )

+ 307
- 0
writer_python.py View File

@ -0,0 +1,307 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
from writer import *
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
BASE_LENGTH = 60
BASE_INDENT = " "
INDENT_LIST = {}
class PythonWriter(Writer):
# 文件后缀
def suffix(self):
return ".py"
# 文件注释(千万不要加时间,影响svn)
def comment(self):
comment = [
'## Automatic generation from -->>'
'\n## excel file name: ' + self.doc_name +
'\n## excel sheet name: ' + self.sheet_name,
'\ndefmodule ' + self.base_name.title() + ' do\n\n'
]
return "\n".join( comment )
# 获取缩进字符串
def indent_ctx( self,indent ):
if indent <= 0: return ""
if indent not in INDENT_LIST:
INDENT_LIST[indent] = ""
else:
ctx = BASE_INDENT*indent
INDENT_LIST[indent] = ctx
return INDENT_LIST[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 )
comment = self.comment_text[k]
val_type = type( lk )
if str == val_type :
lk = ':' + lk.replace("\"", "")
key = "".join( [" def get(",lk,") do\n"] )
val = "".join( [" ## ", comment, "\n", key, " ", lv, "\n end\n\n"] )
dict_text_list.append( val )
dict_str = "".join( dict_text_list )
dict_str = dict_str + " def get(_) do\n :undefined\n end\n\nend"
return False, dict_str
def list_to_text(self, value, indent):
list_text_list = []
# 先定义 struct
struct_text_list = []
struct_len = len(self.comment_text)
tem_count = 0
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 :
lk = ':' + lk.replace("\"", "") + ','
else :
lk = ':' + lk.replace("\"", "")
if None == comment :
comment = ""
val = "".join( [lk.ljust(20, " "), "\t## ", comment, "\n"] )
struct_text_list.append( val )
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 ) :
# 生成对应的 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 )
key_list.append(lv)
all_key_list.append(key_list)
tem = ", ".join( key_list )
key = "".join( [" def get(",tem,") do\n %", self.base_name.title(), "{\n "] )
# 生成对应的value
value_list = []
onedict_len = len(onedict)
tem_count = 0
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 )
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 )
value_list_str = " ".join(value_list)
end_str = "".join( [key, value_list_str, " }\n end\n\n"] )
list_text_list.append( end_str )
underline_list = []
for i in self.keys_list :
underline_list.append('_')
end_str = ", ".join(underline_list)
no_match_str = " def get(" + end_str + ") do\n :undefined\n end\n\n"
list_text_list.append(no_match_str)
# 生成 get_all() 函数
get_all_fun = []
allkey_len = len(all_key_list)
tem_count = 0
for i, ival in enumerate(all_key_list) :
tem_count += 1
if tem_count != allkey_len :
oneval = '{' + ", ".join(ival) + '},\n'
get_all_fun.append(oneval)
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"] )
list_text_list.append( end_str )
# 生成 get_list() 函数
get_list_fun = []
keys_len = len(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 :
get_tem_dict = {}
underline_list = []
for i, ival in enumerate(all_key_list) :
key_tem_list = []
j = 0
underline_list = []
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) :
oldlist = get_tem_dict[keystr]
oldlist.append(ival)
get_tem_dict[keystr] = oldlist
else :
get_tem_dict[keystr] = [ival]
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) :
tem_count += 1
if tem_count != value_len :
oneval = '{' + ", ".join(lval) + '},\n'
value_tem_list.append(oneval)
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"] )
get_list_fun.append(end_str)
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 )
return False, dict_str
# 转换为erlang 文本数据 之前解析出来的excel数据存放方式存在LIST(array格式)和DICT(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)
# python的dict转换为elixir的map类型
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 )
val_type = type( lk )
if str == val_type :
lk = lk.replace("\"", "\'")
key = "".join( [lk," => "] )
val = "".join( [key, lv] )
dict_ctx_list.append(val)
dict_str = ", ".join( dict_ctx_list )
return False,"".join( ["%{",dict_str,"}"] )
# python的list转换为elixir的list类型
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 )
list_str = ", ".join( list_ctx_list )
return False,"".join( ["[",list_str,"]"] )
# python的tuple转换为elixir的tuple类型
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 )
# 返回 {a,b,c}这种不换行的格式
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 :
# 1001.0 -->> 001 去除多余小数点
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] )

+ 133
- 0
writer_xml.py View File

@ -0,0 +1,133 @@
#! python
# -*- coding:utf-8 -*-
import os
import sys
from xml.dom.minidom import Document
from writer import *
try:
basestring
except NameError:
basestring = str
try:
long
except NameError:
long = int
# python3中没有unicode了
try:
unicode
except NameError:
unicode = str
# 加上不确定的层级缩进,60比较合适
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=(',', ':') )
class XmlWriter(Writer):
# 文件后缀
def suffix(self):
return ".xml"
# 注释开始
def comment_start(self):
return "<!--"
# 注释结束
def comment_end(self):
return "-->"
#创建根元素
def root_element(self):
root = self.doc.createElement( self.base_name )
return root
# dict类型转换为xml
def dict_to_xml(self,root,value):
# 需要对key排序,不然每次导出的xml字段是乱的,对版本管理不友好
for k in sorted( value ) :
v = value[k]
sub_root = self.doc.createElement( k )
self.to_xml( sub_root,v )
root.appendChild( sub_root )
# list类型转换为xml
def list_to_xml(self,root,value):
for k,v in enumerate( value ) :
# xml中并不支持array,用item来命名,外加一个index属性
sub_root = self.doc.createElement( "item" )
sub_root.setAttribute( "index",str( k ) )
self.to_xml( sub_root,v )
root.appendChild( sub_root )
# tuple类型转换为xml
def tuple_to_xml(self,root,value):
valueList = list(value)
for k,v in enumerate( valueList ) :
# xml中并不支持array,用item来命名,外加一个index属性
sub_root = self.doc.createElement( "item" )
sub_root.setAttribute( "index",str( k ) )
self.to_xml( sub_root,v )
root.appendChild( sub_root )
# 转换为xml节点
def to_xml(self,root,value):
sub_node = None
val_type_str = None
val_type = type( value )
if int == val_type :
# python3中没有Long类型,int64也用int表示
val_type_str = "int64"
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 :
val_type_str = "number"
# 去除带小数时的小数点,100.0 ==>> 100
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 :
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 )
# 类型为dict或者list的,没有这个type属性
if val_type_str : root.setAttribute( "type",val_type_str )
if sub_node : root.appendChild( sub_node )
# 文件内容
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=" " )

Loading…
Cancel
Save