Python获取Word文档中文字、表格及其中内容(Win11)

由于在网上找了很多博客,跑了很多代码,却依然无法完整的提取出word中的文字和表格,有的表格能成功提取出文字,有的表格却又提取不出,因此便自己试着写了写。

安装python-docx包后,运行下面这段代码,将从Word中提取出文字、表格,并将表格中的文字按照原文的顺序插入到段落文字中,一并返回。

当前的Word版本为Win11新版,将Word上传到Ubuntu上运行此段代码也能得出正确结果,仅支持.docx文件,不支持.doc文件。

from docx import Document     # python install python-docx

def get_doc_content(file_path):
    """
    Get content in .docx, including text, table.
    """
    if file_path.endswith('.docx'):
        doc = Document(file_path)
        content = ""
        cnt = 0   # 记录当前遍历到的表格数
        for element in doc.element.body:
            if element.tag.endswith("p"):  # 段落元素
                paragraph = element.xpath(".//w:t")
                if paragraph:
                    text = ''.join([node.text for node in paragraph if node.text])
                    content += text + "\n"
            elif element.tag.endswith("tbl"):  # 表格元素
                for row in doc.tables[cnt].rows:
                    row_text = '\t'.join(cell.text.strip() for cell in row.cells if cell.text)
                    content += row_text + "\n"
                cnt += 1
        return content
    else:
        print("Cannot process .doc files, only .docx files are supported.")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Endymion

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值