同一页面中提到的 oodocx 模块将用户引导至似乎不存在的 /examples 文件夹。
我已经阅读了 python-docx 0.7.2 的文档,以及我在 Stackoverflow 中可以找到的有关该主题的所有内容,所以请相信我已经完成了我的“作业”。
Python 是我唯一知道的语言(初学者+,也许是中级),所以请不要假设有任何 C、Unix、xml 等知识。
任务:打开一个包含单行文本的 ms-word 2007+ 文档(为了简单起见),并用其字典值替换“字典”中该行文本中出现的任何“关键”单词。然后关闭文档,保持其他一切不变。
文本行(例如)“我们将徘徊在大海的密室中。”
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