首页 技术 正文
技术 2022年11月18日
0 收藏 447 点赞 2,586 浏览 3740 个字

利用Python的字符串处理模块,开发者能够编写脚本用来生成那些格式同样的C、C++、JAVA源程序、头文件和測试文件,从而避免大量的反复工作。

本文概述两种利用Python string类生成java源码的方法。

1。String Template

Template是一个好东西,能够将字符串的格式固定下来,反复利用。Template也能够让开发者能够分别考虑字符串的格式和其内容了。无形中减轻了开发者的压力。

Template属于string中的一个类,有两个重要的方法:substitute和safe_substitute。替换时使用substitute()。若未能提供模板所需的所有參数值时会发生异常。使用safe_substitute() 则会替换存在的字典值,保留未存在的替换符号。

要使用的话可用下面方式调用:

fromstringimportTemplate

Template有个特殊标示符$,它具有下面的规则:

(1)主要实现方式为$xxx,当中xxx是满足python命名规则的字符串,即不能以数字开头、不能为keyword等;

(2)假设$xxx须要和其它字符串接触时,用{}将xxx包裹起来。

开发者通过编写template文件,并通过Template方法创建模板、substitute方法替换字符串就可以快捷的生成所需的文件。编写template文件时一定要注意“$”的使用,由于Python会将以“$”开头的字符串理解成须要替换的变量。

2,replace

    str.replace(old, new[, max])

Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串)。假设指定第三个參数max,则替换不超过 max 次。

模板文件tenplate.java(自:基于模板的简易代码生成器Python源代码

/**
* created since ${now}
*/
package com.alipay.mspcore.common.dal.ibatis;
import java.util.Date;
import junit.framework.Assert;
import com.alipay.mspcore.common.dal.daointerface.${testObject}DAO;
import com.alipay.mspcore.common.dal.dataobject.${testObject};
import com.alipay.sofa.runtime.test.AnnotatedAutowireSofaTestCase;
import com.iwallet.biz.common.util.money.Money;
/**
* @author ${author}
* @version ${version}: MBIM_Service${testObject}_Device.java, ${now} ${author}
*/
public class Ibatis${testObject}DAOTester extends AnnotatedAutowireSofaTestCase {
@Override
public String[] getConfigurationLocations() {
return new String[] { "META-INF/spring/common-dal-db.xml",
"META-INF/spring/mobilespcore-common-dal-dao.xml", "META-INF/spring/common-dal.xml" };
}
@Override
public String[] getResourceFilterNames() {
return new String[] { "META-INF/spring/common-dal-db.xml" };
}
@Override
public String[] getWebServiceConfigurationLocations() {
return new String[] {};
}
private ${testObject}DAO get${testObject}DAO() {
${testObject}DAO dao = (${testObject}DAO) this.getBean("${testObjVarName}DAO", ${testObject}DAO.class, null);
return dao;
}
public void test${testObject}DAO() {
${testObject}DAO configDAO = get${testObject}DAO();
Assert.assertNotNull(configDAO);
}
public void test() {
${testObject}DO ${testObjVarName}DO = new ${testObject}DO();
${testObjVarName}DO.setGmtCreate(new Date());
${testObjVarName}DO.setGmtModified(new Date());
${testObjVarName}DO.setId(10000);
${testObject}DAO ${testObjVarName}DAO = get${testObject}DAO();
long result = ${testObjVarName}DAO.insert(${testObjVarName}DO);
Assert.assertTrue(result > 0);
}
}

Python代码

import os
import datetime
from string import TemplatetplFilePath = 'D:\\Project\\Python\\code_gen\\template.java'
path = 'D:\\Project\\Python\\code_gen\\'testObjList = ['Basic_connect',\
'Sms',\
'Phonebook',\
]for testObj in testObjList: testObjVarName = testObj[0].lower() + testObj[1:] filename = 'MBIM_Service_' + testObj +'_device.java'
author = 'AidanZhang'
version='V0.1' now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') tplFile = open(tplFilePath)
gFile = open(path+filename ,"w") #method 1 with Template and substitute(safe_substitute)
lines=[]
tmp=Template(tplFile.read()) lines.append(tmp.substitute(
author = author,
now = now,
testObject = testObj,
testObjVarName = testObjVarName,
version = version)) gFile.writelines(lines)
'''
#Method 2, with replace
fileList = tplFile.readlines() for fileLine in fileList:
line = fileLine.replace('${author}',author)\
.replace('${now}',now)\
.replace('${testObject}',testObj)\
.replace('${version}',version)\
.replace('${testObjVarName}',testObjVarName)
print line
gFile.writelines(line)
'''
tplFile.close()
gFile.close()
print 'generate %s over. ~ ~' % (path+filename)

执行结果

generate D:\Project\Python\code_gen\MBIM_Service_Basic_connect_device.java over. ~ ~
generate D:\Project\Python\code_gen\MBIM_Service_Sms_device.java over. ~ ~
generate D:\Project\Python\code_gen\MBIM_Service_Phonebook_device.java over. ~ ~
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,961
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,485
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,330
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,113
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,746
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,780