然后,只需要将ClassName替换为定义的类名,将定义的变量组合成 变量声明列表、构造函数参数列表、赋值函数列表,替换掉VariableList,DefaultInitializationList,ConstructorParameterList, ParameterInitializationList, AssignmentList。
Python代码只需完成一些 字符串的组合,替换等。
import sys # Load the sys module (导入sys模块)
import string
def ReplaceStrings(stringlist, fromString, toString):
for i in range(0, len(stringlist)):
s = stringlist[i]
s = string.replace(s, fromString, toString);
stringlist[i] = s
#print stringlist[i]
f = open("template.txt") # template.txt
templateTextLines = f.readlines() # Read all lines into a list (读出所有行到一个列表)
f.close()
f = open('declare.txt')#(sys.argv[1]) # Filename on the command line (从命令行读取文件名)
declareLines = f.readlines() # Read all lines into a list (读出所有行到一个列表), strip all space and \n
f.close()
typeString = ""
nameString = ""
variableListstring = ""
constructorParameterListString = ""
defaultInitialListString = ""
parameterListString = ""
assignmentListString = ""
for i in range(1, len(declareLines)):
lineString = declareLines[i]
lineString = lineString.lstrip()
lineString = lineString.rstrip()
lineString = lineString.rstrip("\n")
if lineString == "": # 跳过空行
continue
splittedStrings = lineString.split()
if len(splittedStrings) > 1: #假定类型和变量名是两个字符串,后续修改:因为有的类型不止一个字符串如unsigned int
typeString = splittedStrings[0]
nameString = splittedStrings[1]
variableListstring += lineString + "; \n "
if typeString=="int" or typeString=="float" or typeString=="double" or typeString=="UInt32" or typeString=="Int32" or typeString == "Float32": # 可自行增加
constructorParameterListString += typeString + " _" + nameString + ", " #基本类型,采用传值的方式
else:
constructorParameterListString += "const " + typeString + " &_" + nameString + ", " #自定义类型,采用传引用方式
defaultInitialListString += nameString + "()\n, "
parameterListString += nameString + "(_" + nameString + ")\n, "
assignmentListString += nameString + " = rhs." + nameString + "; \n "
variableListstring = variableListstring.rstrip(" \n ") # 去掉多余的尾部符号
constructorParameterListString = constructorParameterListString.rstrip(", ")
defaultInitialListString = defaultInitialListString.rstrip("\n, ")
parameterListString = parameterListString.rstrip("\n, ")
assignmentListString = assignmentListString.rstrip(" \n ")
ReplaceStrings(templateTextLines, "ClassName", declareLines[0].strip("\n").strip())
ReplaceStrings(templateTextLines, "VariableList", variableListstring)
ReplaceStrings(templateTextLines, "DefaultInitializationList", defaultInitialListString)
ReplaceStrings(templateTextLines, "ConstructorParameterList", constructorParameterListString)
ReplaceStrings(templateTextLines, "ParameterInitializationList", parameterListString)
ReplaceStrings(templateTextLines, "AssignmentList", assignmentListString)
f = open("out.txt","w") # Open file for writing
for s in templateTextLines:
f.write(s)
# print s
f.close()