获取docx文件内容,及处理docx内图片(docx、textract)

分别用docx和textract进行处理,docx可以将文档分成文字和图片分别进行处理,而textract直接将文档识别成txt格式。

但是用docx处理可能会出现,文档类型就是.docx,但是报如下错误或者说这个文件是压缩文件(压缩文件这个我试过解压再进行处理,还是会说文档类型的错误)

KeyError: "There is no item named 'docProps/thumbnail.jpeg' in the archive"y
#方式一:用docx处理
#但是针对文字和表格要分开:
#文字是按段落进行遍历的
    document = docx.Document('文件路径')
    for i in range(len(document.paragraphs)):
        paragraph = document.paragraphs[i].text
#表格数据,是按表遍历,然后再按行遍历,之后按每行的每个单元格进行遍历
    document = docx.Document('文件路径')
    row_index = 0
    #表
    for table in document.tables:
        # print(table)
        #表行
        for row_index, rows in enumerate(table.rows):
        #表行每单元
            for cell in rows.cells:
            #获取单元格数据
                cell_text = cell.text
#方式二:textract处理
#将整个docx文档识别成文本
        text_file=textract.process(file_path)
    # text_file格式是bytes的格式,将bytes转换成str,才可进行字符串相关操作
        str_text=str(text_file, encoding='utf-8')

注:两个方法都不能对图片进行识别内容提取

文档内图片部分解决办法:

首先获取图片(通过docx实现),代码如下

doc = docx.Document(conplate_path)  # 打开文件
for rel in doc.part._rels:
       rel = doc.part._rels[rel]  # 获得资源
       if "image" not in rel.target_ref:
                 continue
       imgName = re.findall("/(.*)", rel.target_ref)[0]
       with open(subImgPath + "/" + imgName, "wb") as f:
                 f.write(rel.target_part.blob)

图片处理方法:基于python的图片识别_qq_41110377的博客-CSDN博客 

猜你喜欢

转载自blog.csdn.net/qq_41110377/article/details/128733367