用 Python 的 Template 類生成文件報告

string.Template。https://github.com/DahlitzFlorian/generate-file-reports-using-pythons-template-class)上找到整篇文章中使用的代碼示例。string.Template相對于其他解決方案的優(yōu)勢。pip install命令安裝。Jinja2和Mako之類的模板引擎已被廣泛使用。但是,在本文介紹的方案中,這些功能是過分地夸大了。string.Template類背后的動機之后,我們將看一下第一個實際示例。想象一下,您正在一家公司工作,該公司發(fā)布有關(guān)過去一年出版的最佳書籍的年度報告。2020年是特殊的一年,因為除了您的年度報告之外,您還會發(fā)布有史以來最好的書籍清單。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類!我們首先創(chuàng)建實際的模板,如下所示。在這里,我們將文件稱為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/[email protected]/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文件。首先,我們導(dǎo)入所需的兩個內(nèi)置模塊,并從JSON文件加載數(shù)據(jù)。#?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接受一個字符串,而不是一個文件路徑。因此,您還可以提供在程序中先前創(chuàng)建的字符串,而無需將其保存到文件中。就我們而言,我們提供了template.html文件的內(nèi)容。replace()方法將占位符元素替換為存儲在變量內(nèi)容中的字符串。該方法返回一個字符串,我們將其存儲在變量final_output中。最后但并非最不重要的一點是,我們創(chuàng)建了一個名為report.html的新文件,并將最終輸出寫入該文件。final_output?=?template.substitute(elements=content)
with?open("report.html",?"w")?as?output:
????output.write(final_output)
report.html文件,則可以看到結(jié)果。safe_substitution()方法string.Template用例,在結(jié)束本文之前,我想與您分享一個常見情況及其解決方案:安全替換。它是什么?#?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類以及使用它的原因,而且還實現(xiàn)了第一個文件報告腳本!此外,您已經(jīng)了解了safe_substitution()方法以及在哪種情況下使用它可能會有所幫助。更多閱讀
特別推薦

點擊下方閱讀原文加入社區(qū)會員
評論
圖片
表情
