python读取pdf、doc、docx、ppt、pptx文件内容

使用python读取文件,其中pdf、docx、pptx可以直接读,.ppt和.doc文件不能直接读,需要转换成.pptx和.docx文件,并且需要区分系统
如果是linux系统,请先安装组件

#doc2docx
yum install -y libreoffice-headless
yum install -y libreoffice-writer

# ppt2pptx
yum install epel-release -y
yum install libgdiplus -y
pip3 install aspose.slides

python代码如下:

import os


def read_pptx(fp):
    import pptx
    prs = pptx.Presentation(fp)
    for i, slide in enumerate(prs.slides):
        # if i == 1:  在这里可以指定提取ppt的具体页数
        for shape in slide.shapes:
            if shape.has_text_frame:
                text_frame = shape.text_frame
                print(str(i) + '页:' + text_frame.text)


def read_ppt(fp):
    import platform
    os_type = platform.system()
    if os_type == "Windows":
        import win32com.client as wc
        powerpoint = wc.Dispatch("PowerPoint.Application")
        wc.gencache.EnsureDispatch("PowerPoint.Application")
        powerpoint.Visible = 1
        ppt = powerpoint.Presentations.Open(fp)
        ppt.SaveAs(fp+"x")
        powerpoint.Quit()
    elif os_type == "Linux":
        import aspose.slides as slides
        with slides.Presentation(fp) as presentation:
            presentation.save(fp+"x", slides.export.SaveFormat.PPTX)
    read_pptx(fp+"x")

def read_docx(fp):
    import docx
    file = docx.Document(fp)
    print("段落数:" + str(len(file.paragraphs)))  # 段落数为13,每个回车隔离一段
    # 输出每一段的内容
    for para in file.paragraphs:
        print(para.text)

def read_doc(fp):
    import platform
    os_type = platform.system()
    if os_type == "Windows":
        import doc2docx
        doc2docx.convert(fp,fp+"x")
    elif os_type == "Linux":
        import subprocess
        subprocess.check_output(["soffice", "--headless", "–-invisible", "--convert-to", "docx", fp, "--outdir", fp+"x"])
    read_docx(fp + "x")


def read_pdf(fp):
    import pdfplumber
    pdfFile = open(fp,"rb")
    pdf = pdfplumber.open(pdfFile)
    for page in pdf.pages:
        text = page.extract_text()
        print(text)


# file_path = "*.pptx"
file_path = "*.ppt"
# file_path = "*.docx"
# file_path = "*.doc"
# file_path = "*.pdf"
file_extension = os.path.splitext(file_path)[-1].lower()
print("文件后缀:" + file_extension)
if file_extension == '.pptx':
    print("读取pptx文件")
    read_pptx(file_path)
elif file_extension == '.ppt':
    print("读取ppt文件")
    read_ppt(file_path)
elif file_extension == ".docx":
    print("读取docx文件")
    read_docx(file_path)
elif file_extension == ".doc":
    print("读取doc文件")
    read_doc(file_path)
elif file_extension == ".pdf":
    print("读取pdf文件")
    read_pdf(file_path)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值