Python 文件内容读取

背景

计划实现文件中心,支撑检索常见文件内容

依赖包

#pip install baidu-aip
from aip import AipOcr
#pip install xlrd
import xlrd
import os
#pip install csv23
import csv23
#pip install docx2txt
import docx2txt
#pip install pypiwin32
from win32com import client as wc
#pip install python-pptx
from pptx import Presentation
#pip install wand
from wand.image import Image
# 使用 wand 异常,缺少 ImageMagick 支持
# http://docs.wand-py.org/en/latest/guide/install.html#install-imagemagick-on-windows
# https://imagemagick.org/script/download.php#windows
# 使用 wand 异常,FailedToExecuteCommand `"gswin32c.exe"
# http://ghostscript.com/download/gsdnld.html

基础文件读取

.txt

# 读取 txt 文件,返回文件内容 
def readTxt(fileUrl):
    content = ""
    if os.path.exists(fileUrl):
        with open(fileUrl, 'r') as f:
            for l in f:
                temp = l.rstrip('\n').rstrip().split('\t')[0]
                content += temp.replace(' ','')
    return content

.xls .xlsx

# 读取 excel 文件,返回文件内容 
def readExcel(fileUrl):
    content = ""
    if os.path.exists(fileUrl):
        excelfile = xlrd.open_workbook(fileUrl)
        for name in excelfile.sheet_names():
            sheet = excelfile.sheet_by_name(name)
            sheet_rows = sheet.nrows
            sheet_cols = sheet.ncols
            for rowi in range(sheet_rows):
                temp = sheet.row_values(rowi)
                content += (''.join(map(str,temp))).replace(' ','')
    return content

.docx

# 读取 docx 文件    
def readDocx(fileUrl):
    content = ""
    if os.path.exists(fileUrl):
        content = docx2txt.process(fileUrl)
        content = "".join(content.split())
    return content

.doc

# 读取 doc 文件,安装 pypiwin32,操作本地word程序,将doc 转为docx,再调用读取 docx 文件方法
def readDoc(fileUrl):
    AbsolutePath = os.path.abspath(fileUrl)
    word = wc.Dispatch('Word.Application')
    doc = word.Documents.Open(AbsolutePath)
    # 保存临时文件
    doc.SaveAs(AbsolutePath + ".docx", 12, False, "", True, "", False, False, False, False) # 转化后路径下的文件 
    doc.Close()
    word.Quit()
    content = readDocx(fileUrl + ".docx")
    # 移除临时文件
    os.remove(fileUrl + ".docx")
    return content

其他文件读取

.csv

# 读取 csv 文件,返回文件内容,默认utf-8,如果解析不了,使用gbk解析
def readCsv(fileUrl):
    content = ""
    if os.path.exists(fileUrl):
        try:
            with csv23.open_csv(fileUrl) as reader:
                for row in reader:
                    content += (''.join(row)).replace(' ','')
        except Exception as e:
            with csv23.open_csv(fileUrl, encoding='gbk') as reader:
                for row in reader:
                    content += (''.join(row)).replace(' ','')
    return content

图片

# 读取 图片 文件,返回文件内容 
def readImage(fileUrl):
    content = ""
    if os.path.exists(fileUrl):
        APP_ID = 'xxxxx'
        API_KEY = 'xxxxxxxxxxxxxxxx'
        SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxx'
        client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
        with open(fileUrl,'rb') as f:
            img = f.read()
            msg = client.basicGeneral(img)
            for i in msg.get('words_result'):
                temp = i.get('words')
                content += temp.replace(' ','')
    return content

.pptx

# 读取 pptx 文件 ,默认读取正文,默认不读取表格,默认不读取图片
def readPptx(fileUrl,extend_table = False,extend_image = False):
    content = ""
    ppt = Presentation(fileUrl)

    for slide in ppt.slides:
        for shape in slide.shapes:
            if not shape.has_text_frame:
                # 提取图片文字
                if extend_image and hasattr(shape,'image'):
                    # 图片存储本地
                    with open(shape.image.filename, 'wb') as f:
                        f.write(shape.image.blob)
                        f.close()
                    # 调用图片文字识别
                    content += readImage(shape.image.filename)
                    # 移除临时图片
                    os.remove(shape.image.filename)
                # 提取表格内容
                if extend_table and shape.has_table:
                    for row in shape.table.rows:
                        for cell in row.cells:
                            content += cell.text
            else:
                content += shape.text

    content = "".join(content.split())
    return content

.ppt

# 读取 ppt 文件,安装 pypiwin32,操作本地ppt程序,将ppt 转为pptx,再调用读取 pptx 文件方法
def readPpt(fileUrl,extend_table = False,extend_image = False):
    AbsolutePath = os.path.abspath(fileUrl)
    powerpoint = wc.Dispatch('PowerPoint.Application')
    ppt = powerpoint.Presentations.Open(AbsolutePath)
    # 保存临时文件
    ppt.SaveAs(AbsolutePath + ".pptx") 
    powerpoint.Quit()
    content = readPptx(fileUrl + ".pptx",extend_table,extend_image)
    # 移除临时文件
    os.remove(fileUrl + ".pptx")
    return content

.pdf

# 读取 pdf 文件
def readPdf(fileUrl):
    content = ""
    # 将pdf文件转为jpg图片文件
    # ./PDF_FILE_NAME 为pdf文件路径和名称
    image_pdf = Image(filename=fileUrl,resolution=300)    
    image_jpeg = image_pdf.convert('jpg')
         
    # wand已经将PDF中所有的独立页面都转成了独立的二进制图像对象。我们可以遍历这个大对象,并把它们加入到req_image序列中去。    
    req_image = []
    for img in image_jpeg.sequence:
        img_page = Image(image=img)
        req_image.append(img_page.make_blob('jpg'))
     
    # 遍历req_image,保存为图片文件

    for img in req_image:
        ff = open(fileUrl+'.jpg','wb')
        ff.write(img)
        ff.close()
        # 调用图片文字识别
        content += readImage(fileUrl+'.jpg')
        # 移除临时图片
        os.remove(fileUrl+'.jpg')
    return content

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容