• python-Template字符串模板的使用



    前言

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


    一、Template说明

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

    二、使用步骤

    1.导入组件

    Template为string中的一个组件:

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

    2.定义字符串

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

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

    3.转换字符串模板

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

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

    4.声明字典变量

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

    # 声明字典变量,可同时设置初始值
    params = {"times":10, "modelName":"car", "modelType":"1000"}
    
    # 在循环过程中每次更新index的值
    for index in range(1, params["times"] + 1):
        params["index"] = index
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    三、完整示例

    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)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    2.运行结果

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


    总结

    • 使用$标识需替换的变量;
    • 使用Template(str)定义字符串模板;
    • 使用params={}字典键值对的形式定义变量及其需要替换的结果值;
    • 使用substitute(dict)safe_substitute(dict)方法执行替换。
  • 相关阅读:
    模型融合——stacking原理与实现
    雷达电子战实例及经验教训 (03)
    商城项目14_商品新增vo抽取、修改vo、新增逻辑、代码的具体落地、SPU检测、SKU检测、流程图
    supervisor 使用文档
    ClickHouse为什么那么快
    【计算机毕业设计】23.网上商城购物系统+vue
    基本的UDP套接字编程
    【 第十四章 网络编程要素(IP和端口,网络通信协议),实现TCP的网络编程】
    米软科技 | 推进医院智慧管理分级评估体系建立、提升评级
    【QT】QT Designer控件随窗口大小自适应
  • 原文地址:https://blog.csdn.net/qq_28913223/article/details/124973950