使用 Python docx 在 Word 中创建拼音指南/ 'Ruby text'?

Use Python docx to create phonetic guide / 'Ruby text' in Word?

我想为 MS Word 中的单词添加注音指南。在 MS Word 中,原始单词称为 'Base text',拼音指南称为 'Ruby text.'

这是我尝试在 Word 中创建的内容:

docx 文档的页面讨论了 运行 级别的内容,并引用了 ruby:<xsd:element name="ruby" type="CT_Ruby"/> 位于此处: https://python-docx.readthedocs.io/en/latest/dev/analysis/features/text/run-content.html

我不知道如何在我的代码中访问这些。

这是我的一项尝试的示例:

import docx
from docx import Document
document = Document()
base_text = '光栄'
ruby_text = 'こうえい'
p = document.add_paragraph(base_text)
p.add_run(ruby_text).ruby = True
document.save('ruby.docx')

但此代码仅returns以下内容:

光栄こうえい

我尝试在 paragraphp.text 上使用 ruby,删除 = True,但我不断收到错误消息 'X object has no attribute 'ruby'

有人可以告诉我如何完成这个吗?

谢谢!

您提到的 <xsd:element name="ruby" ... 摘录来自 运行 的 XML 架构类型。这意味着 CT_Ruby 类型的子元素可以出现在具有标签名称 <w:ruby>.

的 运行 元素 (<w:r>) 上

python-docx 中还没有对这个元素的任何 API 支持,所以如果你想使用它,你需要使用 [=23= 来操作 XML ] lxml 来电。您可以访问 run._r 上的 运行 元素。如果您在 "python-docx workaround function" 和 "python-pptx workaround function" 上搜索,您会找到一些这样做来扩展功能的示例。