【问题标题】:Convert text to HTML comment in Python在 Python 中将文本转换为 HTML 注释
【发布时间】:2014-05-01 02:46:51
【问题描述】:

我有一个生成一些 HTML 的 Python 脚本。它使用the Python markdown library 这样做。我想将原始 Markdown 文本粘贴在 HTML 末尾的注释中,它有时对调试有用。我试过在 HTML 结束后插入 Markdown 文本,但它对我不起作用(Firefox)。所以我想象这个工作的方式是我运行 Markdown,然后在 HTML 之后简单地附加 Markdown 源,标记为注释。然而,HTML 显然对它在 cmets 中允许的内容有些挑剔。 htmlhelp.com 网站经过一番讨论后给出以下建议:

因此,请使用以下简单规则来组成有效且可接受的 [便携式] cmets:
HTML 注释以“”开头,并且在注释中的任何位置均不包含“--”或“>”。
(source)

所以看起来我需要做一些转义或一些事情来让我的一堆 Markdown 文本变成 HTML 将接受作为评论的表单。是否有现成的工具可以帮助我做到这一点?

【问题讨论】:

    标签: python markdown html


    【解决方案1】:

    根据w3

    Comments consist of the following parts, in exactly the following order:
    
    - the comment start delimiter "<!--"
    - text
    - the comment end delimiter "-->"
    
    The text part of comments has the following restrictions:
    
    1. must not start with a ">" character
    2. must not start with the string "->"
    3. must not contain the string "--"
    4. must not end with a "-" character
    

    这些都是非常简单的规则。您可以对它们进行正则表达式执行,但它们非常简单,您甚至不需要!

    4 个条件中的 3 个可以通过串联来满足,另一个可以通过简单的replace() 来满足。 总而言之,它是一条线

    def html_comment(text):
        return '<!-- ' + text.replace('--', '- - ') + ' -->'
    

    注意空格。

    【讨论】:

    • 不是第一次我发布的问题的解决方案如此简单。有几个奇怪的情况,比如'---'.replace('--', '- -') == '- --',你的代码没有按照我想要的方式处理(仍然是连续两个连字符),所以我目前正在使用'&lt;!-- ' + text.replace('--', '_-_-_').replace('&gt;', '&amp;gt;') + ' --&gt;'
    • 所以最后,事情并不是那么简单 :) 我会更新答案以反映您的更改。如果这是您最终使用的内容,请考虑将其标记为已接受,以使未来的读者受益
    【解决方案2】:

    你就不能.replace吗?最终,您可以用 anything 替换这些字符,但用转义码替换可能不会比不替换任何内容更易读。

    commented = '<!-- %s -->' % markdown_text.replace('--', '').replace('>', '')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 2014-04-02
      • 2022-01-11
      相关资源
      最近更新 更多