簡體   English   中英

有沒有一種方法可以提高PyPDF2.PdfFileReader的文件讀取速度。 讀取多個文件需要太多時間

[英]Is there a way to increase the file reading speed of PyPDF2.PdfFileReader. It takes too much time to read multiple files

我有一個代碼,可通過讀取pdf文件的內部數據來搜索.pdf文件。 我的解決方案為我提供了正確的文件,但是速度很慢。 有沒有辦法使其更快?

keyword = keyword.lower()

for subdir, dirs, files in os.walk(folder_path):
    for file in files:
        filepath = subdir + os.sep + file
        fpath = subdir + os.sep
        if(keyword in file.lower()):
            if filepath not in tflist:
                tflist.append(os.path.join(filepath))
        if filepath.endswith(".pdf"):
            if filepath not in tflist:
                with open(os.path.join(fpath,file), "rb") as f:
                    reader = PyPDF2.PdfFileReader(f)
                    for i in range(reader.getNumPages()):
                        page = reader.getPage(i)
                        page_content = page.extractText().lower()
                        if(keyword in page_content):
                            tflist.append(os.path.join(filepath))
                            break
                            #print (str(1+reader.getPageNumber(page)))
                            #print(keyword)

print(tflist)

您可以做的是使用multiprocessing.Pool

將您的代碼分為兩部分。 第一部分使用os.walk生成路徑列表。 我們將此稱為list_of_filenames

第二部分是一個函數,該函數讀取文件並根據您的條件為每個頁面返回文件名和TrueFalse

def worker(path):
    rv = {}
    with open(path, "rb") as f:             
        reader = PyPDF2.PdfFileReader(f)       
        for i in range(reader.getNumPages()):
            page = reader.getPage(i)
            page_content = page.extractText().lower()
            if(keyword in page_content):
                 rv[i] = True
            else:
                 rv[i] = False
    return (path, rv)

像這樣使用它:

 import multiprocessing as mp

 p = mp.Pool()
 for path, rv in p.imap_unordered(worker, list_of_filenames):
     print('File:', path)
     print('Results:', rv)

假設您的CPU具有n個內核,那么它​​的運行速度將比每次僅處理一個文件快大約n倍。

暫無
暫無

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

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