将 reStructuredText 解析为 HTML [英] Parsing reStructuredText into HTML

查看:66
本文介绍了将 reStructuredText 解析为 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我熟悉优秀的 Sphinx,但我从未解析过 reStructuredText.我想象了一个函数,它接受一串 reStructuredText,可能还有几个附加参数,并返回一串 HTML.

于是我研究了Docutils,它负责解析reStructuredText.我完全不明白如何找到这个功能.网络上的文档参差不齐.docutils.parsers.rst 模块中的许多函数似乎都是针对文件名的.我没有文件名!我只是在处理字符串.

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

有谁知道如何将 reStructuredText 解析成 HTML?

解决方案

试试这个:

<预><代码>>>>从 docutils.core 导入 publish_string>>>publish_string("*anurag*", writer_name='html')

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

<预><代码>>>>从 docutils.core 导入 publish_parts>>>打印publish_parts("*anurag*", writer_name='html')['html_body']<p><em>anurag</em></p>

I'm making a framework in which I let developers describe their package using reStructuredText. I want to parse that reStructuredText into HTML so I can show it in a GUI.

I'm familiar with the excellent Sphinx, but I've never otherwise parsed reStructuredText. I imagined something like a function that takes a string of reStructuredText, and possibly several additional arguments, and returns a string of HTML.

So I looked into Docutils, which is responsible for parsing reStructuredText. I couldn't understand at all how to find this function. Documentation on the web is spotty. Many of the functions in the docutils.parsers.rst module seemed to be geared toward filenames. I don't have filenames! I'm just handling strings.

I tried creating a Parser and a Document and using the parse method, but I just get an error about a missing .tab_width setting.

Does anyone know how to parse reStructuredText into HTML?

解决方案

Try something like this:

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

publish_string accepts a strings and outputs a string or you can use publish_parts to get specific parts of html document e.g.

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

这篇关于将 reStructuredText 解析为 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆