【问题标题】:python reading header from word docxpython从word docx读取标题
【发布时间】:2019-12-12 15:11:37
【问题描述】:

我正在尝试使用 python-docx 和看门狗从 word 文档中读取标题。 我正在做的是,每当创建或修改新文件时,脚本都会读取文件并获取标题中的内容,但我得到一个

docx.opc.exceptions.PackageNotFoundError: Package not found at 'Test6.docx'

错误,我尝试了所有方法,包括将其作为流打开,但没有任何效果,是的,文档已填充。 作为参考,这是我的代码。

**main.py**
    import time
    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler
    import watchdog.observers
    import watchdog.events
    import os
    import re
    import xml.dom.minidom
    import zipfile
    from docx import Document


    class Watcher:
        DIRECTORY_TO_WATCH = "/path/to/my/directory"

        def __init__(self):
            self.observer = Observer()

        def run(self):
            event_handler = Handler()
            self.observer.schedule(event_handler,path='C:/Users/abdsak11/OneDrive - Lärande', recursive=True)
            self.observer.start()
            try:
                while True:
                    time.sleep(5)
            except:
                self.observer.stop()
                print ("Error")

            self.observer.join()


    class Handler(FileSystemEventHandler):

        @staticmethod
        def on_any_event(event):
            if event.is_directory:
                return None

            elif event.event_type == 'created':
                # Take any action here when a file is first created.
                path = event.src_path
                extenstion = '.docx'
                base = os.path.basename(path)

                if extenstion in path:
                    print ("Received created event - %s." % event.src_path)
                    time.sleep(10)
                    print(base)
                    doc = Document(base)
                    print(doc)
                    section = doc.sections[0]
                    header = section.header
                    print (header)



            elif event.event_type == 'modified':
                # Taken any action here when a file is modified.
                path = event.src_path
                extenstion = '.docx'
                base = os.path.basename(path)
                if extenstion in base:
                    print ("Received modified event - %s." % event.src_path)
                    time.sleep(10)
                    print(base)
                    doc = Document(base)
                    print(doc)
                    section = doc.sections[0]
                    header = section.header
                    print (header)



    if __name__ == '__main__':
        w = Watcher()
        w.run()

编辑: 尝试将扩展名从 doc 更改为 docx 并且有效,但无论如何都可以打开 docx,因为这就是我所发现的。

另一件事。打开“.doc”文件并尝试读取标题时,我得到的只是

<docx.document.Document object at 0x03195488>
<docx.section._Header object at 0x0319C088>

我要做的是从标题中提取文本

【问题讨论】:

    标签: python ms-word python-docx python-watchdog


    【解决方案1】:

    您正在尝试打印对象本身,但是您应该访问它的属性:

    ...
    doc = Document(base)
    section = doc.sections[0]
    header = section.header
    print(header.paragraphs[0].text)
    

    根据https://python-docx.readthedocs.io/en/latest/user/hdrftr.html)

    更新

    当我使用 python-docx 包时,结果发现 PackageNotFoundError 非常通用,因为它可能只是因为文件由于某种原因无法访问 - 不存在、未找到或由于权限而发生,以及文件是否为空或损坏。例如,在看门狗的情况下,很可能会在触发“created”事件之后和创建 Document 文件之前发生重命名、删除等情况。由于某种原因,您使这种情况更有可能发生在创建 Document 之前等待 10 秒?所以,尝试检查文件是否存在:

    if not os.path.exists(base):
        raise OSError('{}: file does not exist!'.format(base))
    doc = Document(base)
    

    更新2

    另请注意,当打开程序根据文件名创建一些锁定文件时,可能会发生这种情况,例如在 linux 上运行代码并使用 libreoffice 打开文件会导致

    PackageNotFoundError: Package not found at '.~lock.xxx.docx#'
    

    因为这个文件不是docx文件!所以你应该用

    更新你的过滤条件
    if path.endswith(extenstion):
    ...
    

    【讨论】:

    • 谢谢,但是你有解决其他问题的方法吗?
    • @abodsakka 你的意思是 PackageNotFoundError?我想知道,这些文件是如何创建的,它们是 doc 还是 docx?因为 python-docx 只适用于 docx。
    • 1.当我使用 .doc 作为文档时,它可以工作,但是当我使用 .docx 作为文档时,它会向我抛出一个找不到包的错误。 2. 这些文档是在 Microsoft Word 2019 中创建的。 3. 是的,基本的东西是一个错误,我正在尝试看看这是否可能由于某种原因起作用,但它没有,然后我放弃并发布了这个问题XD
    • @abodsakka 你试过通过文件对象打开吗?我还不清楚重命名是否只是帮助或以不同格式保存 Microsoft Word 中的文档?您可以比较两个不同的文档(它们应该是里面的xml)吗?可能还不支持最新格式的 MW,或者您需要将您的 python-docx 更新到最新版本...
    • 是的,我尝试通过文件系统打开,这实际上是我尝试的第一件事。是的,只需将文件从“.docx”扩展名重命名为“.doc”就可以了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多