簡體   English   中英

Python 寫一個循環的方式 function 可以接受自定義函數

[英]Python way to write a looping function that can accept customizable functions

我有一個 function 我經常用來循環 PDF,把每一頁變成文本,然后在里面做各種事情,然后輸出結果。

def loop_through_PDF(filename):
 
    with fitz.open(filename) as doc:
        try:
            text = ""
        
            for count, page in enumerate(doc, start = 1):

                text = page.getText()

                if text is not None:
                    # apply various functions to text

                    # create results document(s)

            try:
                doc.save(f'{filename}_new.pdf')
                st.info("PDF saved successfully")
            except Exception as e:
                print(e)

        except Exception as e:
            print(e)
    return

很基本的問題。 構造這個 function 以便它易於重用並且我可以輕松地在循環中“插入”不同的動作(函數)的 Pythonic 方法是什么? 我是不是倒過來了? “做事”功能是否應該以某種方式調用“按頁”循環?

為什么不直接在參數中執行操作(函數)?

def loop_through_PDF(filename, action):
    ...


def some_action(text):
    ...


loop_through_PDF(..., some_action)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM