zoukankan      html  css  js  c++  java
  • 数据预处理之抽取文本信息

    抽取文本信息(支持doc、docx、pdf)

    环境要求:Python3.6 ; pycharmIDE ;anaconda

    需要插件:win32com

    ps:建议使用---->在cmd中使用python -m pip install pypiwin32进行安装

    # coding=utf-8
    
    import os, fnmatch  # fnmatch 匹配后缀名的包
    from win32com import client as wc
    from win32com.client import Dispatch, gencache
    
    
    def Files2txt(filePath, savePath=''):
        try:
            # 切分文件目录和文件名
            dirs, filename = os.path.split(filePath)
            # 修改转化后的文件名
            typename = os.path.splitext(filename)[-1].lower()
            new_name = TranType(filename, typename)
            # 文件转化后的保存路径
            if savePath == '':
                savePath = dirs
            else:
                savePath = savePath
            new_save_path = os.path.join(savePath, new_name)
            print('保存路径:', new_save_path)
            # 加载处理应用
            manyapp = wc.Dispatch('Word.Application')
            mytxt = manyapp.Documents.Open(filePath)
            mytxt.SaveAs(new_save_path, 4)
            mytxt.Close()
            print('处理完成,请查看!')
        except Exception as e:
            print('程序出错了!')
    
    def TranType(filename, typename):
        '''
        根据文件后缀修改文件名
        1、文件名  2、文件类型后缀
        返回修改后的新的文件名
        '''
        new_name = ''
        if typename == '.pdf':
            if fnmatch.fnmatch(filename, '*.pdf'):
                new_name = filename[:-4] + '.txt'
            else:
                return
        elif typename == '.doc' or typename == '.docx':
            if fnmatch.fnmatch(filename, '*.doc'):
                new_name = filename[:-4] + '.txt'
            elif fnmatch.fnmatch(filename, '*.docx'):
                new_name = filename[:-5] + '.txt'
            else:
                return
        else:
            print('警告:
     您输入【', typename, '】不合法,工具仅支持pdf/doc/docx格式,请输入正确的格式。')
            return
        return new_name
    
    
    if __name__ == '__main__':
        filepath1 = os.path.abspath(r'D:Pythonstudy	est抽取文本信息智联范本.docx')
        Files2txt(filepath1)

    未完待续...

  • 相关阅读:
    几何——BAPC2019 K
    dsu on tree —— BAPC2019 A
    概率dp——BAPC2019 L
    计算几何+三分求极值——cf1046I
    上下文管理器
    转 -- 一行式
    转--python 基础
    转--python 面试题
    转 -- Python: 多继承模式下 MRO(Method Resolution Order) 的计算方式关乎super
    转--python之正则入门
  • 原文地址:https://www.cnblogs.com/nixindecat/p/10909394.html
Copyright © 2011-2022 走看看