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,具體接口詳情看百度開發者文檔。
python-pptx官方文檔:https://python-pptx.readthedocs.io/en/latest/api/slides.html#pptx.slide.Slides