Question

I am using the python library docx: http://github.com/mikemaccana/python-docx

My goal is to open a file, replace certain words, then write the file with replacement.

My current code:

#! /usr/bin/python

from docx import *

openDoc = "test.docx"
writeDoc = "test2.docx"
replace = {"Test":"TEST"}

document = opendocx(openDoc)
docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]

print getdocumenttext(document)

for key in replace:
    if search(docbody, key):
        print "Found" , key , "replacing with" , replace[key]
        docbody = replace(docbody,key,replace[key])

print getdocumenttext(document)

# ideally just want to mirror current document details here..
relationships = relationshiplist()
coreprops = coreproperties(title='',subject='',creator='',keywords=[])

savedocx(document,coreprops,appproperties(),contenttypes(),websettings(),wordrelationships(relationships),'a.docx')

` However I get the following error:

Traceback (most recent call last):
  File "process.py", line 17, in <module>
    docbody = replace(docbody,key,replace[key])
TypeError: 'dict' object is not callable

I have no idea why this is happening, but I think it has something to do with the docx module. Can anyone explain why this is happening?

Thanks

Was it helpful?

Solution

You assigned replace to a dictionary at the very top:

replace = {"Test":"TEST"}

So you cannot use the replace() method, because the word replace is now pointing to a dictionary - instead of what I suspect is some method from your library.

Rename your dictionary and it should work.

OTHER TIPS

It's a matter of ambiguity , there are two types of "replace" used in your code, on as a function call and the other one as the name of your own defined dictionary , the python interpreter is interpreting the type of replace to be a dict so you can't use it as a function call, try changing the name of your replace dictionary to see if it's solved :

for key in replace:
    if search(docbody, key):
        print "Found" , key , "replacing with" , replace[key]
        docbody = **replace**(docbody,key,**replace**[key])

You used import * with docx, so you have a function "replace" and a dictionary "replace". This confuses the interpreter. Instead, use "import docx" and then use docx.replace(...), or rename your "replace" dictionary to something else. I recommend the first option, as this avoids similar naming clashes in the future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top