python提取ppt文本_提取PPT中的文字(包括图片中的文字)

python是一门很强大的语言,因为有着丰富的第三方库,所以可以说Python是无所不能的。

很多人都知道,Python可以操作Excel,PDF·还有PPT,这篇文章就围绕Python提取PPT中的文字来写,包括提取PPT中的艺术字,图片中的文字。

因为实现环境是linux,所以无法用win32com来实现这个需求,使用extract库也可以提取PDF,PPT等文件中的文字,但这里不用extract来实现,用python-pptx,如果熟悉extract库一点的也知道,extract中也使用了python-pptx,实现过程也是调用了python-pptx。

presentation = pptx.Presentation(fp)

results = []

for slide in presentation.slides:

for shape in slide.shapes:

if shape.has_text_frame:

for paragraph in shape.text_frame.paragraphs:

part = []

for run in paragraph.runs:

part.append(run.text)

results.append(''.join(part))

elif isinstance(shape, Picture):

content = self.parsepic.request_api(shape.image.blob)

results.append(''.join(content))

results = [line for line in results if line.strip()]

代码分析:

presentation = pptx.Presentation(fp)

实例化ppt对象,只有实例化Presentation对象才能操作ppt,通过此对象可以访问其他类的接口。

通过presentation访问幻灯片presentation.slides,slides是由每一个幻灯片对象组成的列表。

通过幻灯片对象slide访问包含在此幻灯片上的形状对象shape,如文本框,表格,图片等

if shape.has_text_frame

判断形状对象是否为文本对象

for paragraph in shape.text_frame.paragraphs:

part = []

for run in paragraph.runs:

part.append(run.text)

results.append(''.join(part))

获取文本框的文本,文本框中也会出现多个段落内容

elif isinstance(shape, Picture):

content = self.parsepic.request_api(shape.image.blob)

results.append(''.join(content))

判断是否为图片对象或者艺术字对象,这里是调用百度图片提取文字的接口来提取PPT中包含在图片中的文字。

def request_api(self, img_data):

url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'

# 高进度版

# url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic'

postdata = {

'language_type': 'CHN_ENG', # 中英文混合

'detect_direction': 'true',

'image': base64.b64encode(img_data)

}

headers = {

'Content-Type': 'application/x-www-form-urlencoded',

'User-Agent': random.choice(USER_AGENT['pc'])

}

r = requests.post(url, params={'access_token': self.get_token()}, data=postdata, headers=headers).json()

if r.get('error_code'):

raise Exception(r['error_msg'])

return [item['words'] for item in r['words_result']]

需要注册一个账号,并且开通图片提取文字的服务,获取APPKEY, APPSECRETKEY,从而获取到token,具体接口详情看百度开发者文档。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值