【问题标题】:Render a c program into a html using python使用python将c程序渲染成html
【发布时间】:2020-12-17 00:57:57
【问题描述】:

任务是使用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 诠释主要(无效){ printf("Hello World!"); }

但我得到的是

#包括 诠释主要(无效){ printf("Hello World!"); }

我这样做有两个问题:

  1. “printf...”行之前的缩进也应该反映在 HTML 中。
  2. c代码中的&lt;stdio.h&gt;在渲染时被视为HTML标签,我需要它作为html中的文本。

注意:约束

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

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

你能给我一些建议吗?

【问题讨论】:

  • 使用&lt;pre&gt;标签可能吗?那应该保持缩进。

标签: python jinja2


【解决方案1】:

我使用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>

【讨论】:

  • 谢谢@carson。这是我需要的解决方案。你是怎么知道 Django 模板中的这个东西的?试过的时候没注意?谢谢你的回复!
  • 说来话长,过几天回复你。 TLDR,我阅读了 Django-template 源代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多