获取word文件信息

读取doc,docx文件

  1. 使用office,wps工具打开文件另存为

  2. 针对doc文件,antiword 提取doc文件信息

    2.1 安装

    • windows

      1、 下载zip包 地址:http://www.winfield.demon.nl/
      2、 解压至指定目录,配置系统环境变量path
      3、 使用antiword命令行操作doc文件
      
    • Linux

      1、 wget http://www.winfield.demon.nl/linux/antiword-0.37.tar.gz
      2、 tar -zxvf antiword-0.37.tar.gz
      3、 cd antiword-0.37
      4、 make && make install
      

    2.2 使用说明

    • antiword -t xxx.doc 输出文件信息
    • antiword -f xxx.doc 格式化输出文件信息
    • antiword -f xxx.doc >> xxx.txt 读取doc文件信息并保存为txt文件
  3. 针对docx文件,使用python-docx包

    • pip install python-docx
    def trans_docx_txt(path):
        '''
        fun: docx 文件转txt文件
        '''
        newpath = "".join(path.split(".")[:-1]) + ".txt"
        # 保存的文件如果存在需要先删除
        if os.path.exists(newpath):
            os.remove(newpath)
        # 空文件不处理
        if os.path.getsize(path) == 0:
            return
    
        file = docx.Document(path)
        # 读取段落
        for paragraph in file.paragraphs:
            if paragraph.text:
                with open(newpath, "a+", encoding="utf-8") as file:
                    file.write(paragraph.text + "\n")
    
        file = docx.Document(path)
        # 如果存在表格,读取表中单元格信息
        if file.tables:
            for table in file.tables:
                row_count = len(table.rows)
                colu_count = len(table.columns)
                for i in range(row_count):
                    for j in range(colu_count):
                        with open(newpath, "a+", encoding="utf-8") as file:
                            file.write(table.cell(i, j).text + "\n")
    
posted @ 2020-03-11 13:46  今日店休  阅读(374)  评论(0编辑  收藏  举报