文章目录

  • 一、Template说明
  • 二、Python字符串替换的几种方法
  • 1.适用于变量少的单行字符串替换
  • 2.字符串命名格式化符替换
  • 3.模版方法替换


一、Template说明

1.定义字符串
根据需要,设置字符串中需要替换的字符以${变量名称}的形式显示。

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

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

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

3.声明字典变量

  • 使用字典存储需替换的变量名称及目标替换值,采用{“key”:“value”}的形式。
# 声明字典变量,可同时设置初始值
params = {"times":10, "modelName":"car", "modelType":"1000"}

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

4.替换字符串模板

  • 采用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)
#!/usr/bin/env python3 

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+= tmpInstance

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

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

结果:

<?xml version="1.0" ?>
<Instances>
	<Instance id="car_1" type="1000"/>
	<Instance id="car_2" type="1000"/>
	<Instance id="car_3" type="1000"/>
	<Instance id="car_4" type="1000"/>
	<Instance id="car_5" type="1000"/>
	<Instance id="car_6" type="1000"/>
	<Instance id="car_7" type="1000"/>
	<Instance id="car_8" type="1000"/>
	<Instance id="car_9" type="1000"/>
	<Instance id="car_10" type="1000"/>
</Instances>

其他eg:

>>> import string
查看string是否已经导入
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'string']
类相关文档
>>> help(string)
>>>> help(string.Template)

二、Python字符串替换的几种方法

1.适用于变量少的单行字符串替换

template = "hello %s , your website  is %s " % ("大CC","http://blog.me115.com")
print(template)

format函数的语法方式:
template = "hello {0} , your website  is {1} ".format("大CC","http://blog.me115.com")
print(template)

2.字符串命名格式化符替换

使用命名格式化符,这样,对于多个相同变量的引用,在后续替换只用申明一次即可;

template = "hello %(name)s ,your name is %(name), your website  is %(message)s" %{"name":"大CC","message":"http://blog.me115.com"}
print(template)


format函数的语法方式:
template = "hello {name} , your name is {name}, your website  is {message} ".format(name="大CC",message="http://blog.me115.com")
print(template)

3.模版方法替换

使用string中的Template方法;

  • 通过字典传递参数:
from string import Template

tempTemplate  = Template("There ${a} and ${b}")
d={'a':'apple','b':'banbana'}
print(tempTemplate.substitute(d))


或者
tempTemplate  = Template("There ${a} and ${b}")
d={'a':'apple','b':'banbana'}
print(tempTemplate.substitute(a='apple',b='banbana'))

总结:
使用$标识需替换的变量;
使用Template(str)定义字符串模板;
使用params={}字典键值对的形式定义变量及其需要替换的结果值;
使用substitute(dict)或safe_substitute(dict)方法执行替换。

参考: