用 Python 的 Template 类生成文件报告

string.Template。https://github.com/DahlitzFlorian/generate-file-reports-using-pythons-template-class)上找到整篇文章中使用的代码示例。string.Template相对于其他解决方案的优势。pip install命令安装。Jinja2和Mako之类的模板引擎已被广泛使用。但是,在本文介绍的方案中,这些功能是过分地夸大了。string.Template类背后的动机之后,我们将看一下第一个实际示例。想象一下,您正在一家公司工作,该公司发布有关过去一年出版的最佳书籍的年度报告。2020年是特殊的一年,因为除了您的年度报告之外,您还会发布有史以来最好的书籍清单。data.json的JSON文件,其中包含作者姓名和书名的映射,如下所示。{
    "Dale Carnegie": "How To Win Friends And Influence People",
    "Daniel Kahneman": "Thinking, Fast and Slow",
    "Leo Tolstoy": "Anna Karenina",
    "William Shakespeare": "Hamlet",
    "Franz Kafka": "The Trial"
}
string.Template类!我们首先创建实际的模板,如下所示。在这里,我们将文件称为template.html。html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Great Books of All Timetitle>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
head>
<body>
    <div class="container">
        <h1>Great Books of All Timeh1>
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">#th>
                    <th scope="col">Authorth>
                    <th scope="col">Book Titleth>
                tr>
            thead>
            <tbody>
                ${elements}
            tbody>
        table>
    div>
body>
html>
tbody元素中,使用了一个占位符$ {elements}来标记我们稍后将注入书籍列表的位置。report.py的新Python文件。首先,我们导入所需的两个内置模块,并从JSON文件加载数据。# report.py
import json
import string
with open("data.json") as f:
    data = json.loads(f.read())
data变量是一个字典,其中包含作者的名称(键)和书名(值)作为键值对。接下来,我们生成HTML表,将其放入模板中(还记得占位符吗?)。因此,我们初始化一个空字符串,向其添加新的表行,如下所示。content = ""
for i, (author, title) in enumerate(data.items()):
    content += ""
    content += f"{i + 1} "
    content += f"{author} "
    content += f"{title} "
    content += " "
with open("template.html") as t:
    template = string.Template(t.read())
string.Template接受一个字符串,而不是一个文件路径。因此,您还可以提供在程序中先前创建的字符串,而无需将其保存到文件中。就我们而言,我们提供了template.html文件的内容。replace()方法将占位符元素替换为存储在变量内容中的字符串。该方法返回一个字符串,我们将其存储在变量final_output中。最后但并非最不重要的一点是,我们创建了一个名为report.html的新文件,并将最终输出写入该文件。final_output = template.substitute(elements=content)
with open("report.html", "w") as output:
    output.write(final_output)
report.html文件,则可以看到结果。safe_substitution()方法string.Template用例,在结束本文之前,我想与您分享一个常见情况及其解决方案:安全替换。它是什么?# safe_substitution.py
import string
template_string = "Your name is ${firstname} ${lastname}"
t = string.Template(template_string)
result = t.substitute(firstname="Florian", lastname="Dahlitz")
print(result)
KeyError。为避免这种情况,我们可以利用safe_substitution()方法。在这种情况下,safe意味着Python在任何情况下都尝试返回有效字符串。因此,如果找不到任何值,则不会替换占位符。# safe_substitution.py
import string
template_string = "Your name is ${firstname} ${lastname}"
t = string.Template(template_string)
result = t.safe_substitute(firstname="Florian")
print(result)  # Your name is Florian ${lastname}
Template类以及使用它的原因,而且还实现了第一个文件报告脚本!此外,您已经了解了safe_substitution()方法以及在哪种情况下使用它可能会有所帮助。更多阅读
特别推荐

点击下方阅读原文加入社区会员
评论
