You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用docutils将reStructuredText转为HTML?代码输出异常求助

Fixing reStructuredText to HTML Conversion with docutils

Ah, I see the issue here! Your code is using the default writer for publish_string, which outputs a pseudo-XML representation of the document tree instead of proper HTML. That’s why you’re seeing those escaped tags and raw structure instead of the formatted HTML you expect—unlike the rst2html.py command-line tool, which automatically uses the HTML writer under the hood.

To fix this, you just need to explicitly specify the HTML writer when calling publish_string, and optionally set the output encoding to get a readable string instead of bytes. Here’s your corrected code:

from docutils.core import publish_string

input_string = ("Heading\n" "=======\n" "\n" "1. With 24 widgets pull a **long** one;\n" "2. with fewer, push a **wide** one.\n")

# Use the HTML writer and request unicode output for a clean string
html = publish_string(input_string, writer_name='html', output_encoding='unicode')
print(html)

What’s changed?

  • writer_name='html': This tells docutils to use the same HTML writer that rst2html.py uses, generating proper HTML markup instead of the pseudo-XML tree.
  • output_encoding='unicode': By default, publish_string returns a bytes object. Setting this parameter gives you a Python string directly, making it easier to print or manipulate without extra decoding steps.

When you run this corrected code, you’ll get a full HTML document with your heading, numbered list, and bold text properly formatted—just like the output from rst2html.py.

内容的提问来源于stack exchange,提问作者Psionman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:39:28