python利用win32com读取doc和pdf内容,并保存到文件

将使用win32com包进行处理

读取doc文件

# coding=utf-8
import os, fnmatch
from win32com import client as wc
from win32com.client import Dispatch


def word2txt(filePath, savePath = ''):
    dirs, filename = os.path.split(filePath)
    print(dirs, '\n', filename)
    new_name = ''
    if fnmatch.fnmatch(filename, "*.docx"):
        new_name = filename[:-5] + '.txt'
    if fnmatch.fnmatch(filename, "*.doc"):
        new_name = filename[:-4] + '.txt'
    if savePath == '':
        savePath = dirs
    else:
        savePath = savePath
    word2txtPath = os.path.join(savePath, new_name)
    print(word2txtPath)
    wordappp = wc.Dispatch('Word.Application')
    mytxt = wordappp.Documents.Open(filePath)
    mytxt.SaveAs(word2txtPath, 4) # 4代表抽取结果保存为文本
    mytxt.Close()


if __name__ == '__main__':
    filePath = os.path.abspath(r'./专业课.docx')
    word2txt(filePath)

读取pdf

# coding=utf-8
import os, fnmatch
from win32com import client as wc
from win32com.client import Dispatch

def pdf2txt(filePath, savePath=''):
    dirs, filename = os.path.split(filePath)
    print(dirs, '\n', filename)
    new_name = ''
    if fnmatch.fnmatch(filename, '*.pdf') or fnmatch.fnmatch(filename, '*.PDF'):
        new_name = filename[:-4] + '.txt'
    else:
        print('格式不正确,仅支持pdf格式')
        return
    if savePath == '':
        savePath = dirs
    else:
        savePath = savePath
    pdf2txtPath = os.path.join(savePath, new_name)
    print(pdf2txtPath)
    wordappp = wc.Dispatch('Word.Application')
    mytxt = wordappp.Documents.Open(filePath)
    mytxt.SaveAs(pdf2txtPath, 4)  # 4代表抽取文本
    mytxt.Close()


if __name__ == '__main__':
    filePath = os.path.abspath(r'./论文.pdf')
    pdf2txt(filePath)
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值