python-Template字符串模板的使用


前言

在测试过程中,经常遇到需要造大批量数据的情况,比如JSON数组、XML实例等等,这些文本中的某部分或大段内容相似,且存在某个值或几个值需要修改。遇到此种情况时,使用python模板可以极快速地解决此问题。


一、Template说明

  • Template(str) —— 将字符串内容作为模板使用
  • ${var} —— 字符串中以此形式表示可替换的变量
  • substitute(dict) —— 使用该方法可以替换模板中的变量,参数采用字典键值对形式

二、使用步骤

1.导入组件

Template为string中的一个组件:

# 导入字符串模板组件
from string import Template

2.定义字符串

根据需要,设置字符串中需要替换的字符以${变量名称}的形式显示。
示例:instances、modelName、index、modelType

# 文本结构
start = '''<?xml version="1.0" encoding="UTF-8"?>'''
content = '''<Instances>${instances}</Instances>'''
instance = '''<Instance id="${modelName}_${index}" type="${modelType}"/>'''

3.转换字符串模板

将已定义的字符串使用Template(str)的形式转换为字符串模板。
示例:

# 转换字符串模板
instance_template = Template(instance)
content_template = Template(content)

4.声明字典变量

使用字典存储需替换的变量名称及目标替换值,采用{"key":"value"}的形式。
示例:

# 声明字典变量,可同时设置初始值
params = {"times":10, "modelName":"car", "modelType":"1000"}

# 在循环过程中每次更新index的值
for index in range(1, params["times"] + 1):
    params["index"] = index

5.替换字符串模板

采用substitute(dict)方法可一次性替换模板中的所有变量。
注意:采用substitute替换时需确认所有待替换变量都在字典中存在!或者,也可以选择使用safe_substitute进行替换。

# 变量声明
instances = ''

# 循环造数据
for index in range(1, params["times"] + 1):
    params["index"] = index
    tmpInstance = instance_template.substitute(params)
    instances = instances + tmpInstance

# 替换中心内容
params["instances"] = instances
content = content_template.substitute(params)

三、完整示例

1.全部代码

import os
from string import Template
from xml.dom import minidom

# 参数含义
# filepath: 文本存储路径
# way: 写入方式 w重写 at追加
# content: 文本内容
def make_content(filepath=None, way=None, content=None):
  os.makedirs(os.path.dirname(filepath), exist_ok=True)
  file = open(filepath, way, encoding="utf-8")
  file.write(content)
  file.close()

# 文本结构
start = '''<?xml version="1.0" encoding="UTF-8"?>'''
content = '''<Instances>${instances}</Instances>'''
instance = '''<Instance id="${modelName}_${index}" type="${modelType}"/>'''

# 转换字符串模板
instance_template = Template(instance)
content_template = Template(content)

# 变量声明
instances = ''
filepath = os.getcwd() + "\\demo.xml"
params = {"times":10, "modelName":"car", "modelType":"1000"}

# 循环造数据
for index in range(1, params["times"] + 1):
    params["index"] = index
    tmpInstance = instance_template.substitute(params)
    instances = instances + tmpInstance

# 替换中心内容
params["instances"] = instances
content = content_template.substitute(params)

# 拼接完整内容,并写入文件
outer = start + content
outer_xml = minidom.parseString(outer)
outer_prettyxml = outer_xml.toprettyxml()
make_content(filepath, "w", outer_prettyxml)
print(filepath)

2.运行结果

运行后生成的xml截图:
在这里插入图片描述


总结

  • 使用$标识需替换的变量;
  • 使用Template(str)定义字符串模板;
  • 使用params={}字典键值对的形式定义变量及其需要替换的结果值;
  • 使用substitute(dict)safe_substitute(dict)方法执行替换。
  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值