将reStructuredText解析为HTML

57

我正在制作一个框架,让开发人员使用reStructuredText描述他们的软件包。我想将这些reStructuredText解析为HTML,以便在GUI中显示。

我熟悉出色的Sphinx,但从未解析过reStructuredText。我想象中是一个函数,该函数接受reStructuredText字符串和可能的其他参数,并返回一个HTML字符串。

因此,我研究了负责解析reStructuredText的Docutils。我完全不知道如何找到这个函数。网络上的文档很零散。 docutils.parsers.rst模块中的许多函数似乎都是针对文件名的。但我没有文件名!我只处理字符串。

我尝试创建一个Parser和一个Document,并使用parse方法,但是我只得到一个关于缺少.tab_width设置的错误。

有人知道如何将reStructuredText解析为HTML吗?

1个回答

68

试试像这样:

>>> from docutils.core import publish_string
>>> publish_string("*anurag*", writer_name='html')

publish_string接受字符串并输出字符串,或者您可以使用 publish_parts 获取html文档的特定部分。

>>> from docutils.core import publish_parts
>>> print publish_parts("*anurag*", writer_name='html')['html_body']
<p><em>anurag</em></p>

5
你的第二个建议更加有效: 'body' 恰好是我想要的。 - Ram Rachum
3
你应该链接到文档(http://docutils.sourceforge.net/docs/api/publisher.html#publish-parts-details)!此外,以下是一些相关的代码片段:http://code.activestate.com/recipes/193890-using-rest-restructuredtext-to-create-html-snippet/。 - Dr. Jan-Philip Gehrcke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接