使用 python 将 c 程序渲染为 html

Render a c program into a html using python

任务是使用python

将c程序渲染成HTML文件

这是我的代码

from jinja2 import Template

html_template = '''
    <html>
        <body>
            <div>
            {% for i in code %}  {{i}}<br> {% endfor %}
            </div>
        </body> 
    </html>'''

# reading c program file
file_content = open("prog.c",'r').readlines()
template = Template(html_template)
html_content = template.render(code = file_content)

with open('outp.html','w') as f:
    f.write(html_content)

考虑 prog.c 文件包含

#include <stdio.h>
int main(void) {
    printf("Hello World!");
    }

HTML 输出应该是


    #include <stdio.h>
    int main(void) {
        printf("Hello World!");
        }

但我得到的是


    #include
    int main(void) {
    printf("Hello World!");
    }

我这样做有两个问题:

  1. 'printf...' 行之前的缩进也应反映在 HTML。
  2. c代码中的<stdio.h>在渲染时被认为是HTML标签,我需要它作为html中的文本。

注意:约束

  1. 不应更改 prog.c 文件,因为它始终是动态的。

您可以使用 python 字符串格式或 jinja 模板,这取决于您,我只需要一个解决方案。

你能给我一些建议吗?

我用django.template实现的

(我喜欢 django-template 风格。但别担心。它的风格与 jinja 非常相似)

from django.template import Template, Engine, Context

file_content = '''
#include <stdio.h>
int main(void) {
    printf("Hello World!");
    }
'''

html_template = '''
    <html>
        <body>
            <pre>{% for i in code %}{{i}}<br>{% endfor %}</pre>
        </body> 
    </html>'''

t = Template(html_template, engine=Engine())
result = t.render(Context(dict(code=[_ for _ in file_content.split('\n') if _ != ''])))
result_compress = ''.join([_.strip() for _ in result.split('\n') if _.strip()])
with open('outp_compress.html', 'w') as f:
    f.write(result_compress)
print(result_compress)
with open('outp.html', 'w') as f:
    f.write(result)
print(result)


在浏览器中查看

在浏览器中打开如下所示。

#include <stdio.h>
int main(void) {
    printf("Hello World!");
    }

文本内容

outp_compress.html

<html><body><pre>#include &lt;stdio.h&gt;<br>int main(void) {<br>    printf(&quot;Hello World!&quot;);<br>    }<br></pre></body></html>

outp.html


    <html>
        <body>
            <pre>#include &lt;stdio.h&gt;<br>int main(void) {<br>    printf(&quot;Hello World!&quot;);<br>    }<br></pre>
        </body> 
    </html>