python-TypeError:';dict';对象不可调用

python-TypeError:';dict';对象不可调用,python,typeerror,docx,python-docx,Python,Typeerror,Docx,Python Docx,我正在使用python库docx: 我的目标是打开一个文件,替换某些单词,然后用替换词写入文件 我当前的代码: #! /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', names

我正在使用python库docx:

我的目标是打开一个文件,替换某些单词,然后用替换词写入文件

我当前的代码:

#! /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')
` 但是,我得到以下错误:

Traceback (most recent call last):
  File "process.py", line 17, in <module>
    docbody = replace(docbody,key,replace[key])
TypeError: 'dict' object is not callable
回溯(最近一次呼叫最后一次):
文件“process.py”,第17行,在
docbody=replace(docbody,key,replace[key])
TypeError:“dict”对象不可调用
我不知道为什么会发生这种情况,但我认为这与docx模块有关。有人能解释为什么会这样吗


感谢您将
replace
指定给位于最顶端的词典:

replace={“Test”:“Test”}

因此,您不能使用
replace()
方法,因为单词
replace
现在指向一个字典,而不是我怀疑的来自您的库的某个方法


重命名您的字典,它应该可以工作。

这是一个模棱两可的问题,代码中使用了两种类型的“替换”,一种作为函数调用,另一种作为您自己定义的字典的名称,python解释器将替换类型解释为dict,因此您不能将其用作函数调用,尝试更改替换词典的名称,以查看是否已解决:

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

您将import*与docx一起使用,因此有一个函数“replace”和一个字典“replace”。这使口译员感到困惑。相反,使用“导入docx”,然后使用docx.replace(…),或者将“replace”字典重命名为其他字典。我推荐第一个选项,因为这样可以避免将来出现类似的命名冲突