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

use*_*022 2 python docx typeerror python-docx

我正在使用python库docx:http://github.com/mikemaccana/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')
Run Code Online (Sandbox Code Playgroud)

`但是我收到以下错误:

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

我不知道为什么会这样,但我认为它与docx模块有关.任何人都可以解释为什么会这样吗?

谢谢

Bur*_*lid 8

您分配replace到最顶层的字典:

replace = {"Test":"TEST"}

所以你不能使用这个replace()方法,因为这个单词replace现在指向一个字典 - 而不是我怀疑你的库中的一些方法.

重命名你的字典,它应该工作.