欢迎访问宙启技术站
智能推送

在HTML报告中嵌入代码片段并使用pygments.formatters.html进行高亮显示

发布时间:2023-12-15 02:00:18

在HTML报告中嵌入代码片段可以通过使用<pre><code>标签来实现。然后,我们可以使用pygments.formatters.html模块来对代码进行高亮显示。

下面是一个示例,展示了如何在HTML中嵌入代码片段,并使用pygments.formatters.html进行高亮显示。

首先,我们需要将代码片段包装在<pre><code>标签中:

<pre>
<code>
  # 在这里插入你的代码
</code>
</pre>

然后,我们需要导入相关的模块,包括pygments.lexerspygments.formatters.html

from pygments import lexers, highlight
from pygments.formatters import html

接下来,我们需要为要高亮显示的代码设置适当的语言:

code = '''
def add_numbers(x, y):
    return x + y
'''

lexer = lexers.get_lexer_by_name("python")

然后,我们可以使用highlight函数将代码高亮显示为HTML:

html_code = highlight(code, lexer, html.HtmlFormatter())

最后,将高亮显示的代码插入到HTML报告中:

report = '''
<!DOCTYPE html>
<html>
<head>
  <title>Code Highlighting Example</title>
  <style>
    .code {
      background-color: #f0f0f0;
      padding: 10px;
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <div class="code">
    {0}
  </div>
</body>
</html>
'''
final_report = report.format(html_code)

在上述代码中,我们首先定义了一个简单的HTML模板,其中包含一个名为.code的类,用于样式化高亮显示的代码。

然后,我们使用{0}占位符将高亮显示的代码插入到HTML模板中,最终得到一个带有高亮显示代码的HTML报告。

完整的代码如下所示:

from pygments import lexers, highlight
from pygments.formatters import html

code = '''
def add_numbers(x, y):
    return x + y
'''

lexer = lexers.get_lexer_by_name("python")
html_code = highlight(code, lexer, html.HtmlFormatter())

report = '''
<!DOCTYPE html>
<html>
<head>
  <title>Code Highlighting Example</title>
  <style>
    .code {
      background-color: #f0f0f0;
      padding: 10px;
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <div class="code">
    {0}
  </div>
</body>
</html>
'''
final_report = report.format(html_code)

with open("code_report.html", "w") as f:
    f.write(final_report)

这将生成一个名为code_report.html的文件,其中包含高亮显示的代码。

希望这个例子对你有所帮助!