提取PPT中的文字(包括圖片中的文字)


python是一門很強大的語言,因為有着豐富的第三方庫,所以可以說Python是無所不能的。

很多人都知道,Python可以操作Excel,PDF·還有PPT,這篇文章就圍繞Python提取PPT中的文字來寫,包括提取PPT中的藝術字,圖片中的文字。

因為實現環境是linux,所以無法用win32com來實現這個需求,使用extract庫也可以提取PDF,PPT等文件中的文字,但這里不用extract來實現,用python-pptx,如果熟悉extract庫一點的也知道,extract中也使用了python-pptx,實現過程也是調用了python-pptx。

  1.  
    presentation = pptx.Presentation(fp)
  2.  
    results = []
  3.  
    for slide in presentation.slides:
  4.  
    for shape in slide.shapes:
  5.  
    if shape.has_text_frame:
  6.  
    for paragraph in shape.text_frame.paragraphs:
  7.  
    part = []
  8.  
    for run in paragraph.runs:
  9.  
    part.append(run.text)
  10.  
    results.append( ''.join(part))
  11.  
    elif isinstance(shape, Picture):
  12.  
    content = self.parsepic.request_api(shape.image.blob)
  13.  
    results.append( ''.join(content))
  14.  
    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

判斷形狀對象是否為文本對象

  1.  
    for paragraph in shape.text_frame.paragraphs:
  2.  
    part = []
  3.  
    for run in paragraph.runs:
  4.  
    part.append(run.text)
  5.  
    results.append( ''.join(part))

獲取文本框的文本,文本框中也會出現多個段落內容

  1.  
    elif isinstance(shape, Picture):
  2.  
    content = self.parsepic.request_api(shape.image.blob)
  3.  
    results.append( ''.join(content))

判斷是否為圖片對象或者藝術字對象,這里是調用百度圖片提取文字的接口來提取PPT中包含在圖片中的文字。

  1.  
    def request_api(self, img_data):
  2.  
    url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
  3.  
    # 高進度版
  4.  
    # url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic'
  5.  
    postdata = {
  6.  
    'language_type': 'CHN_ENG', # 中英文混合
  7.  
    'detect_direction': 'true',
  8.  
    'image': base64.b64encode(img_data)
  9.  
    }
  10.  
    headers = {
  11.  
    'Content-Type': 'application/x-www-form-urlencoded',
  12.  
    'User-Agent': random.choice(USER_AGENT[ 'pc'])
  13.  
    }
  14.  
    r = requests.post(url, params={ 'access_token': self.get_token()}, data=postdata, headers=headers).json()
  15.  
    if r.get( 'error_code'):
  16.  
    raise Exception(r[ 'error_msg'])
  17.  
    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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM