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)

    未完待续...

  • 相关阅读:
    django关闭调试信息,打开内置错误视图
    django 配置URLconf和获取值
    django模版中配置和使用静态文件方法
    django的模型类管理器-----------数据库操作的封装
    美团校招的算法题:灯泡游戏
    ccTouchBegan
    特效effects(二)
    特效effects
    CCProgressTo和CCProgressTimer
    TransitionsTest
  • 原文地址:https://www.cnblogs.com/nixindecat/p/10909394.html
Copyright © 2011-2022 走看看