word文档的python解析

主要两块,第一个是文件类型的转换,第二个是用docx包去对word文档中的table进行parse

1. 文件格式装换

因为很多各种各样的原因,至今还有一些word文档是doc的格式存的,对于这种,如果我们想用python对这个word文档中的内容进行解析的话,理论上必须要处理成docx先。

如果你刚好是个mac的用户,那你可以不用弄了,因为如果你用python+osx的系统,这个就是个无解的事情,可以考虑下用java之类的方式处理。但是幸运的是我找了一台机器是win系统的,然后我就处理了,代码如下:

import os
from win32com import client


def doc_to_docx(path):
    if os.path.splitext(path)[1] == ".doc":
        word = client.Dispatch('Word.Application')
        doc = word.Documents.Open(path)  # 目标路径下的文件
        doc.SaveAs(os.path.splitext(path)[0] + ".docx", 16)  # 转化后路径下的文件
        doc.Close()
        word.Quit()


def find_file(path, ext, file_list=[]):
    dir = os.listdir(path)
    for i in dir:
        i = os.path.join(path, i)
        if os.path.isdir(i):
            find_file(i, ext, file_list)
        else:
            if ext == os.path.splitext(i)[1]:
                file_list.append(i)
    return file_list


if __name__ == "__main__":
    dir_path = "E:\yschen3\pyprogram\线下二维码活动"
    ext = ".doc"
    file_list = find_file(dir_path, ext)
    for file in file_list:
        doc_to_docx(file)
        print(file)

大概就是这样,用了个win32com这个包,非常容易,接下来,我们就可以用python-docx来处理了

2. 表格的处理

这里python有个包教python-dox,就是专门做这个事情的,他可以对段落,表格进行解析和处理。大概说下逻辑

1. 会读出所有的表格

2. 然后对表格里面的行,一行一行的读

3. 真对一行,就是一个格子一个格子的读

这里对于合并处理的单元格,默认的逻辑是,分成两个,写出相同的内容,保持表格维度的一致性,当然这里可以看你的需求,你可以在读取的过程中,做一次简单的去重过滤。

这里代码在这里:

import os
from win32com import client


def doc_to_docx(path):
    if os.path.splitext(path)[1] == ".doc":
        word = client.Dispatch('Word.Application')
        doc = word.Documents.Open(path)  # 目标路径下的文件
        doc.SaveAs(os.path.splitext(path)[0] + ".docx", 16)  # 转化后路径下的文件
        doc.Close()
        word.Quit()


def find_file(path, ext, file_list=[]):
    dir = os.listdir(path)
    for i in dir:
        i = os.path.join(path, i)
        if os.path.isdir(i):
            find_file(i, ext, file_list)
        else:
            if ext == os.path.splitext(i)[1]:
                file_list.append(i)
    return file_list


if __name__ == "__main__":
    dir_path = "E:\yschen3\pyprogram\线下二维码活动"
    ext = ".doc"
    file_list = find_file(dir_path, ext)
    for file in file_list:
        doc_to_docx(file)
        print(file)

猜你喜欢

转载自www.cnblogs.com/chenyusheng0803/p/10634253.html