我有一个用 reStructuredText 编写的博客,目前我在发布新帖子时必须手动将其转换为 HTML。
我正在使用 Google App Engine 编写一个新的博客系统,需要一种将 rst 转换为 HTML 的简单方法。
我不想使用docutils
,因为它太大太复杂。有没有更简单的(理想情况下是单个 python 文件)方法可以做到这一点?
我有一个用 reStructuredText 编写的博客,目前我在发布新帖子时必须手动将其转换为 HTML。
我正在使用 Google App Engine 编写一个新的博客系统,需要一种将 rst 转换为 HTML 的简单方法。
我不想使用docutils
,因为它太大太复杂。有没有更简单的(理想情况下是单个 python 文件)方法可以做到这一点?
docutils 是一个可以安装的库。它还安装了前端工具来从 rest 转换为包括 html 在内的各种格式。
这是一个可以使用的独立工具。
大多数转换器将为此利用 docutils 库。
Sphinx 文档生成器 Python 库包括许多重组文本 (RST) 命令行转换器。
安装狮身人面像:
$ pip install sphinx
然后使用众多 rst2*.py 助手之一:
$ rst2html.py in_file.rst out_file.html
查看破解 docutils的说明。您不需要整个 docutils 从 rst 生成 html,但您确实需要阅读器、解析器、转换器和编写器。通过一些努力,您可以将所有这些组合到现有 docutils 文件中的单个文件中。
好吧,您可以使用以下代码进行尝试,用法是:
compile_rst.py yourtext.rst
或者
compile_rst.py yourtext.rst desiredname.html
# compile_rst.py
from __future__ import print_function
from docutils import core
from docutils.writers.html4css1 import Writer,HTMLTranslator
import sys, os
class HTMLFragmentTranslator( HTMLTranslator ):
def __init__( self, document ):
HTMLTranslator.__init__( self, document )
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
def reST_to_html( s ):
return core.publish_string( s, writer = html_fragment_writer )
if __name__ == '__main__':
if len(sys.argv)>1:
if sys.argv[1] != "":
rstfile = open(sys.argv[1])
text = rstfile.read()
rstfile.close()
if len(sys.argv)>2:
if sys.argv[2] != "":
htmlfile = sys.argv[2]
else:
htmlfile = os.path.splitext(os.path.basename(sys.argv[1]))[0]+".html"
result = reST_to_html(text)
print(result)
output = open(htmlfile, "wb")
output.write(result)
output.close()
else:
print("Usage:\ncompile_rst.py docname.rst\nwhich results in => docname.html\ncompile_rst.py docname.rst desiredname.html\nwhich results in => desiredname.html")
在本地构建文档
Install Python.
Clone the forked repository to your computer.
Open the folder that contains the repository.
Execute: pip install -r requirements.txt --ignore-installed
Execute: sphinx-build -b html docs build
The rendered documentation is now in the build directory as HTML.
如果 Pyfunc 的答案不符合您的需求,您可以考虑改用 Markdown 语言。语法类似于 rst,markdown.py 相当小且易于使用。它仍然不是单个文件,但您可以将其作为模块导入到您可能拥有的任何现有脚本中。