[英]python - TypeError: 'dict' object is not callable
I am using the python library docx: http://github.com/mikemaccana/python-docx 我正在使用python库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. 我不知道为什么会这样,但我认为它与docx模块有关。 Can anyone explain why this is happening?
任何人都可以解释为什么会这样吗?
Thanks 谢谢
You assigned replace
to a dictionary at the very top: 您已将
replace
分配到最顶部的字典:
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. 所以你不能使用
replace()
方法,因为单词replace
现在指向一个字典 - 而不是我怀疑你的库中的某些方法。
Rename your dictionary and it should work. 重命名你的字典,它应该工作。
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 : 这是一个含糊不清的问题,你的代码中使用了两种类型的“替换”,作为函数调用,另一种作为你自己定义的字典的名称,python解释器将替换的类型解释为dict所以你不能将它用作函数调用,尝试更改替换字典的名称以查看它是否已解决:
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". 你使用import *和docx,所以你有一个函数“replace”和一个字典“replace”。 This confuses the interpreter.
这使翻译感到困惑。 Instead, use "import docx" and then use docx.replace(...), or rename your "replace" dictionary to something else.
相反,使用“import docx”然后使用docx.replace(...),或将“replace”字典重命名为其他字典。 I recommend the first option, as this avoids similar naming clashes in the future.
我建议使用第一个选项,因为这样可以避免将来出现类似的命名冲突。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.