同一页面中提到的 oodocx 模块将用户引至似乎不存在的 /examples 文件夹。
我已经阅读了 python-docx 0.7.2 的文档,以及我可以在 Stackoverflow 中找到的关于该主题的所有内容,所以请相信我已经完成了我的“功课”。
Python 是我唯一知道的语言(初学者+,可能是中级),所以请不要假设任何 C、Unix、xml 等知识。
任务:打开一个包含单行文本的 ms-word 2007+ 文档(为了简单起见),并将 Dictionary 中出现在该行文本中的任何“关键”词替换为其字典值。然后关闭文档,保持其他所有内容不变。
一行文字(例如)“我们将在海室中流连。”</p>
from docx import Document
document = Document('/Users/umityalcin/Desktop/Test.docx')
Dictionary = {‘sea’: “ocean”}
sections = document.sections
for section in sections:
print(section.start_type)
#Now, I would like to navigate, focus on, get to, whatever to the section that has my
#single line of text and execute a find/replace using the dictionary above.
#then save the document in the usual way.
document.save('/Users/umityalcin/Desktop/Test.docx')
我在文档中没有看到任何允许我执行此操作的内容 - 也许它在那里,但我不明白,因为在我的级别上没有详细说明所有内容。
我已遵循此站点上的其他建议,并尝试使用该模块的早期版本(https://github.com/mikemaccana/python-docx),该版本应该具有“替换,advReplace 等方法”,如下所示:我打开python解释器中的源代码,并在末尾添加以下内容(这是为了避免与已安装的0.7.2版本冲突):
document = opendocx('/Users/umityalcin/Desktop/Test.docx')
words = document.xpath('//w:r', namespaces=document.nsmap)
for word in words:
if word in Dictionary.keys():
print "found it", Dictionary[word]
document = replace(document, word, Dictionary[word])
savedocx(document, coreprops, appprops, contenttypes, websettings,
wordrelationships, output, imagefiledict=None)
运行它会产生以下错误消息:
NameError:名称'coreprops'未定义
也许我正在尝试做一些无法完成的事情——但如果我错过了一些简单的事情,我会很感激你的帮助。
如果这很重要,我在 OSX 10.9.3 上使用 64 位版本的 Enthought's Canopy