我正在使用string.Template
s 生成Python代码。模板可能看起来像
import numpy
def main():
${content}
return
用多行字符串替换${content}
时,结果为
import numpy
def main():
a = 1
b = 2
print(a + b)
return
有道理,但当然不是我想要的。我可以使用 ; 而不是用换行符连接语句。
,但为了可读性,我希望所有换行符都用正确的缩进填充。
如何用换行字符串和正确的缩进替换 ${content}
?
最佳答案
我也使用 string.Template
进行代码生成,并且还需要从模板中获取缩进。
我的解决方案是子类化 string.Template
并添加一个方法来获取缩进。
如果将多行字符串存储为行列表,则可以使用 '\n' + 缩进
加入此列表。
使用您的示例,代码可能如下所示:
from string import Template
import re
class MyTemplate(Template):
def get_indentation(self):
self.indentation = {}
# self.pattern is the regular expression Template uses to find the substitution patterns
# self.template is the template string given in the constructor
for match in self.pattern.finditer(self.template):
symbol = match.group()
# search whitespace between the start of a line and the current substitution pattern
# '^' matches start of line only with flag re.MULTILINE
pattern = r"^(\s*)" + re.escape(symbol)
indent = re.search(pattern, self.template, re.MULTILINE)
self.indentation[symbol] = indent.group(1)
tpl = """\
import numpy
def main():
${content}
return
"""
template = MyTemplate(tpl)
template.get_indentation()
content_list = [
"a = 1",
"b = 2",
"print(a + b)",
]
join_str = "\n" + template.indentation["${content}"]
content = join_str.join(content_list)
print(template.substitute(content=content))
MyTemplate.get_indentation()
编译一个字典,其中替换模式作为键,从行开头到替换模式开头的空格作为值。所以在这种情况下字典将是:
template.indentation = {
"${content}": " "
}
请注意,代码效率不是很高,因为它使用正则表达式搜索整个模板字符串,以查找在此字符串中找到的每个替换模式。
关于python字符串模板: multiline substitution with correct indentation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751054/