使用Python docx时如何在输出文档中启用拼写?

Col*_*ert 9 python docx python-docx

我正在使用Python docx库来生成一个文档,我希望能够打开并找到拼写错误.但是当我打开文档时,没有任何拼写错误标记(小红色下划线)或者如果我确定进行拼写检查.如果我编辑一行或副本,将内容剪切并粘贴到单词中,拼写功能将按预期工作.

有没有办法让输出文档自动显示/识别输出文档中的拼写错误?我玩过"no_proof"标志,但似乎没有帮助.(在Windows框中使用64位Python 3.4,docx 8.6,在Word 2013中打开输出)

谢谢你的任何想法!

代码重现:

from docx import Document
document = Document()
paragraph = document.add_paragraph('This has a spellling errror')
document.save(r'SpellingTester.docx')
Run Code Online (Sandbox Code Playgroud)

Word输出:

Gen*_*ari 6

我会尝试使用document.settings它包装文档的 lxml 节点元素的对象。正如您从文档中看到的那样hideSpellingErrors属性。

Python DOCX 设置

<xsd:element name="hideSpellingErrors" type="CT_OnOff" minOccurs="0"/>
Run Code Online (Sandbox Code Playgroud)

编辑:在进一步研究之后,我会尝试这样的事情:

import docx

document = docx.Document()

DOCX = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'

element = document.settings.element.find(DOCX + 'proofState')
element.attrib[DOCX + 'grammar'] = 'dirty'
element.attrib[DOCX + 'spelling'] = 'dirty'

document.add_paragraph("This has a spellling errror")
document.save("test.docx")
Run Code Online (Sandbox Code Playgroud)

随着DOCX前缀可以改变,但它很容易在LXML元素读取。我现在不知道是否有办法更直接、更干净地做事,但这对我有用。

有关proofState在 docx 中设置的更多信息:

  • 使用 nsmap 来帮助验证代码的未来:`nsmap = document.settings.element.nsmap; proofstate = document.settings.element.find("w:proofState", nsmap); proofstate.set("{{{}}}grammar".format(nsmap["w"]), "dirty"); proofstate.set("{{{}}}spelling".format(nsmap["w"]), "dirty")` (2认同)