python - 如何修复Python中的 'TypeError: __init__() missing 1 required positional argument: '部分''错误

标签 python python-docx

控制台一直告诉我这个,说缺少一个参数。

"D:\Program Files (x86)\Python\python.exe" D:/workspace/Glossary_Builder_Python/main.py
Please input the file path
C:\Users\Administrator\Desktop\Allergies.docx
Traceback (most recent call last):
  File "D:/workspace/Glossary_Builder_Python/main.py", line 102, in <module>
    main(sys.argv)
  File "D:/workspace/Glossary_Builder_Python/main.py", line 98, in main
    extractWdFrmDocx(filepath)
  File "D:/workspace/Glossary_Builder_Python/main.py", line 18, in extractWdFrmDocx
    document = Document(file)
TypeError: __init__() missing 1 required positional argument: 'part'

我正在尝试使用 python-docx 和 python 3.7 从 docx 文件中提取一些突出显示(黄色)的文本。 当我进入 Document func 时,__init__ 看起来像这样:

def __init__(self, element, part):
    super(Document, self).__init__(element)
    self._part = part
    self.__body = None

那么这里的“部分”是做什么用的?

下面是提取函数和主要函数:

def extractWdFrmDocx(filepath):
    # self.filepath = filepath
    document = Document(filepath)
    for para in document.paragraphs:
        for run in para.runs:
            if run.font.highlight_color == WD_COLOR_INDEX.YELLOW:
                keyText.append(run.text)
    print(keyText)


def main(argv):
    print("Please input the file path")
    filepath = input()
    extractWdFrmDocx(filepath)


if __name__ == "__main__":
    main(sys.argv)

最佳答案

可能您从 docx.document 导入了 Document。您不应该直接构造这样的 Document 对象。相反,创建 Document 对象的函数以 docx.Document 形式提供,它需要一个参数,就像您现在使用它的方式一样。

因此您的代码应该是:

import docx

[...]

document = docx.Document(filepath)

From documentation of python-docx:

Document objects

class docx.document.Document

[...]

Not intended to be constructed directly. Use docx.Document() to open or create a document.

关于python - 如何修复Python中的 'TypeError: __init__() missing 1 required positional argument: '部分''错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57834869/

相关文章:

python - 如何防止我的 Python 应用程序在到达代码末尾时自动关闭?

python - 如何将 pandas 中的秒数替换为零

python - 可以使用python-docx在word文档中插入页面吗?

python - 如何生成 RGBColor(0x42, 0x24, 0xE9) 格式的 RGBcolor

python - 使用 python-docx 合并包含图像的 docx 文件

python - 为什么我的 IDE 无法自动完成 python-docx?

python - 使用混合元组和字符串列重新排序 pandas DataFrame 列

python - 如何模拟 Django 模型管理器的方法?

python正则表达式使用捕获组来定义另一个组长度{}

python - 使用 python-docx 将内容添加到现有的 docx