【问题标题】:Formatting HTML with Python使用 Python 格式化 HTML
【发布时间】:2022-02-04 04:57:55
【问题描述】:

我想在 python 中格式化我的 html 代码。

我的 Python 文件是:

titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
html_text = """<html>
<head>
    <style type="text/css">
        table { border-collapse: collapse;}
        td { text-align: center; border: 5px solid #ff0000; border-style: dashed; font-size: 30px; }
    </style>
</head>
<body>
    <table width="100%" height="100%" border="5px">
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
    </table>
</body>
</html> % (titles[0], titles[1], titles[2], titles[3], titles[4])"""

f = open('temp.html', 'w')
f.write(html_text)
f.close()

我想让这些 %s 成为titles[0]、titles[1]、titles[2]、titles[3]、titles[4]。

我该怎么做?

【问题讨论】:

  • 到目前为止你尝试过什么?编辑:我的坏没有看到滚动框的底部
  • @Brandon 代码,你没看到吗?

标签: python html


【解决方案1】:

您的格式字符串中有两个错误。第一个,正如 U9-Forward 所指出的,在这里:

</html> % (titles[0], titles[1], titles[2], titles[3], titles[4])"""

% 是一个插值运算符,所以它需要字符串和数据之间:

</html>""" % (titles[0], titles[1], titles[2], titles[3], titles[4])

第二个错误,只有在你修复了它之后才会显现出来:

<table width="100%" height="100%" border="5px">

当您使用% 运算符时,字符% 会变得特殊,因此%s 会执行您所期望的操作。但是当这种情况发生时,"100%" 是不合法的,因为正如错误消息告诉你的那样,它会放置一个unsupported format character '"' (0x22) at index 237。通过将光标放在字符串的开头并按右箭头 237 次,您可以在一分钟内自己发现这一点。

在这种情况下,你想留下的%%必须加倍:

<table width="100%%" height="100%%" border="5px">

这给了

html_text = '''<html>
<head>
    <style type="text/css">
        table { border-collapse: collapse;}
        td { text-align: center; border: 5px solid #ff0000; border-style: dashed; font-size: 30px; }
    </style>
</head>
<body>
    <table width="100%%" height="100%%" border="5px">
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
        <tr>
            <td>%s</td>
        </tr>
    </table>
</body>
</html>''' % (titles[0], titles[1], titles[2], titles[3], titles[4])

但这里的根本问题是 Python %-strings 是一种格式化迷你语言,而 HTML 是一种格式化语言,因此像这样构造 HTML 意味着您同时使用两种语言进行编程。这涉及的双重想法给了一些有经验的程序员一个刺激,但我们其他人更乐于分离我们的关注点并一次处理一种语言。代替%-strings,考虑使用lxml 来构建您的HTML。有更多的学习曲线(由优秀的tutorial 缓解),但您的代码将更容易编写和维护,lxml 将确保您的 HTML 没有语法错误。

【讨论】:

    【解决方案2】:

    fstrings 是现在很酷的孩子们使用的。

    titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
    html_text = f"""<html>
    <head>
        <style type="text/css">
            table {{ border-collapse: collapse;}}
            td {{ text-align: center; border: 5px solid #ff0000; border-style: dashed; font-size: 30px; }}
        </style>
    </head>
    <body>
        <table width="100%" height="100%" border="5px">
            <tr>
                <td>{titles[0]}</td>
            </tr>
            <tr>
                <td>{titles[1]}</td>
            </tr>
            <tr>
                <td>{titles[2]}</td>
            </tr>
            <tr>
                <td>{titles[3]}</td>
            </tr>
            <tr>
                <td>{titles[4]}</td>
            </tr>
        </table>
    </body>
    </html>"""
    
    
    with open('temp.html', 'w') as f:
        f.write(html_text)
    

    您将变量放在文本中的{} 中,并且您的样式必须使用双{{}} 进行转义。试试看。

    另外,写入文件的 Pythonic 方式是使用上下文管理器。它处理关闭而不需要.close() 对打开的文件。

    【讨论】:

    • 它给我一个错误:&lt;/html&gt;""" SyntaxError: invalid syntax
    • 它工作得很好,相信我。我在这里运行它。当然,除非您使用 Python 2.x。它必须是 3.x
    • Python 3.6+,具体来说。
    【解决方案3】:

    你可以使用一些template engine that mix logic into template

    jinja2 为例:

    1. 安装pip install jinja2

    2 那么代码将是:

    html_text = """<html>
    <head>...</head>
    <body>
        <table width="100%" height="100%" border="5px">
            {% for title in titles %}
            <tr>
                <td>{{title}}</td>
            </tr>
            {% endfor %}
        </table>
    </body>
    </html>"""
    
    from jinja2 import Template
    titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
    my_templ = Template(html_text)
    with open('temp.html', 'w') as f:
        f.write(my_templ.render(titles=titles))
    

    请注意,处理可变长度列表是灵活的。 模板引擎用于 Web 框架。

    【讨论】:

      【解决方案4】:

      你在错误的地方结束了字符串,所以使用下面的完整代码:

      titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
      html_text = '''<html>
      <head>
          <style type="text/css">
              table { border-collapse: collapse;}
              td { text-align: center; border: 5px solid #ff0000; border-style: dashed; font-size: 30px; }
          </style>
      </head>
      <body>
          <table width="100%" height="100%" border="5px">
              <tr>
                  <td>%s</td>
              </tr>
              <tr>
                  <td>%s</td>
              </tr>
              <tr>
                  <td>%s</td>
              </tr>
              <tr>
                  <td>%s</td>
              </tr>
              <tr>
                  <td>%s</td>
              </tr>
          </table>
      </body>
      </html>''' % (titles[0], titles[1], titles[2], titles[3], titles[4])
      
      f = open('temp.html', 'w')
      f.write(html_text)
      f.close()
      

      所以现在您将获得预期的 HTML 文件。

      【讨论】:

      • 感谢您的快速回答,但您的代码不起作用。它给了我这个错误:ValueError: unsupported format character '"' (0x22) at index 237,我的 HTML 文件也没有改变。
      • @HoseongJeon 错误?
      • @HoseongJeon 然后自己输入,不要使用剪切粘贴...至少要努力。
      • @Jean-BaptisteYunès 我同意你的看法,是的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      相关资源
      最近更新 更多