Article directory
1. Template Description
1. Define the character string
According to the requirement, the character to be replaced in the setting string ${变量名称
is displayed in the form of }.
- Example:instances、modelName、index、modelType
# 文本结构
start = '''<?xml version="1.0" encoding="UTF-8"?>'''
content = '''<Instances>${instances}</Instances>'''
instance = '''<Instance id="${modelName}_${index}" type="${modelType}"/>'''
2. Convert string template
Convert the defined string to a string template in the form of Template(str).
# 转换字符串模板
instance_template = Template(instance)
content_template = Template(content)
3. Declare dictionary variables
- Use a dictionary to store the variable name to be replaced and the target replacement value, in the form of {"key":"value"}.
# 声明字典变量,可同时设置初始值
params = {
"times":10, "modelName":"car", "modelType":"1000"}
# 在循环过程中每次更新index的值
for index in range(1, params["times"] + 1):
params["index"] = index
4. Replace string template
- Use the substitute(dict) method to replace all variables in the template at once.
Note: When using substitute, it is necessary to confirm that all variables to be replaced exist in the dictionary! Alternatively, you can choose to use safe_substitute for substitution.
# 变量声明
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)
result:
<?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>
Other eg:
>>> import string
查看string是否已经导入
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'string']
类相关文档
>>> help(string)
>>>> help(string.Template)
Two, several methods of Python string replacement
1. Suitable for single-line string replacement with few variables
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. String named formatter replacement
Use named formatters, so that for multiple references to the same variable, you only need to declare it once in subsequent replacements;
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. Template method replacement
Use the Template method in string;
- Pass parameters via dictionary:
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'))
Summary:
Use $ to identify variables to be replaced;
use Template(str) to define string templates;
use params={} dictionary key-value pairs to define variables and their result values to be replaced;
use substitute(dict) or safe_substitute(dict ) method performs the substitution.
reference: