問題描述

在 python 中,最優雅的方法是生成 HTML 文檔。我目前手動將所有標籤附加到一個巨大的字符串,並將其寫入一個文件。有更優雅的做法嗎?

最佳解決辦法

我建議使用可用於 python 的許多模板語言之一,例如一個 built into Django(您不必使用其餘的 Django 來使用其模板引擎) – 一個谷歌查詢應該給你很多其他替代模板實現。

我發現,學習模板庫有很多方面的幫助 – 無論何時需要生成 e-mail,HTML 頁面,文本文件或類似文件,您只需編寫一個模板,將其加載到模板庫中,然後讓模板代碼創建完成產品。

這裏有一些簡單的代碼讓你開始:

#!/usr/bin/env python

from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django

# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""

t = Template(template)
c = Context({"title": "title from code",
             "mystring":"string from code"})
print t.render(c)

如果您在磁盤上有模板,請查看 render_to_string 函數,從而可以從預定義的搜索路徑列表中加載模板,並從字符串中填充數據並將其渲染為字符串,這一切都在一個函數調用中。

次佳解決辦法

我發現 yattag 是最優雅的做法。

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('html'):
    with tag('body'):
        with tag('p', id = 'main'):
            text('some text')
        with tag('a', href='/my-url'):
            text('some link')

result = doc.getvalue()

它看起來像 html,附加的好處,你不必關閉標籤。

第三種解決辦法

我建議使用 xml.dom 來做到這一點。

http://docs.python.org/library/xml.dom.html

閲讀本手冊頁,它具有構建 XML(因此 XHTML) 的方法。它使所有 XML 任務更容易,包括添加子節點,文檔類型,添加屬性,創建文本節點。這應該能夠幫助您絕大多數您將要創建的 HTML 。

它也對分析和處理現有的 xml 文檔非常有用。

希望這可以幫助

P.S

這是一個教程,可以幫助您應用語法

http://www.postneo.com/projects/pyxml/

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。