python字符串模板: multiline substitution with correct indentation

标签 python templates newline

我正在使用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/

相关文章:

python - py.test 只找到 5 个项目,但我的类(class)有更多

C++0x : how to get variadic template parameters without reference?

python - 想要打印 "\n"标志而不换行

python - 在基本程序中使用 else 得到错误 : unindent does not match any outer indentation level

python - 从单独文件中的类创建对象

java - 使用 JAX-WS for SOAP 通过其 Web 界面访问 Java 中的远程服务

c++ - 具有默认参数的模板特化

c++ - 参数包的模板推导和显式提供的类型

c# - 使用 StreamWriter 不起作用\n (C#)

python - 我可以避免在Python中的2个for循环之间打印新行吗