如何检测 pdf 的文本何时使用 PyPDF2.extractText 成功提取?



我正在使用pypdf2库通过其extractText函数从PDF文件中提取文本,并且对于大多数PDF,它的效果很好!

但是,有些PDF产生的文本看起来像:

n!&quot#$%&'((&quord , - 。" - 。" 。(/0 $ -1" 2( 3- $。45 n"&quort; quot&quot#$%&'((#' (,$!&quot# - 。# $ -/$ 0.1 &quot美元!%/%0!% n $ 0&quot&quot& $(%1(0,$ 2%3(%0"%0!%&quot& $%1(34 5"%36%1 1(0,$!7 n %% 8%!&quort#$%&'($(%&quort; n%0!%#% , - $(%&quot"%0!%3*9(%40'0!0-9 $% - (%/%#*4%0&quot!$ 967 n %%:%0!%&quot&quort&quord&quot& $%3*9(%$'$ % n1(0,$% , - $(7 n %%; 3%099 !"4#,$ #9%&quort $ 3($,%36%#(0" amp;,$ 052%<%90!& $%1(0,$%6#5&quot'3(0>#03*% n36% , - $(!% - $ $&quot = $&quot = $$ %//em>%//%# 4%:? 7%@(0,$% , - $(!%#($%0*% n6.'78&quort'ab%,$#*!%, 9&quot&quot&quot'c n%&quort; d%e $ 0 $ quot&quot& $(%1(0,$%*3(%53,13!0%%%%%/fd%:bg n%hd%:%%%%%%/?d%hb? n %% fd%:b: n%3(

(

根据文档,这是可以预期的:

这适用于某些PDF文件,但对其他文件来说很差,具体取决于 在使用的发电机上。

不幸的是,当extractText()函数输出如上上述文本时不会引起任何异常。

所以,我的问题是,有没有办法可以通过编程性检测extractText()功能返回Gibberish?

基于 @dyz的评论,这是解决方案。

document_path被假定到您打开的PDF文件的路径。其余的应该是不言而喻的。

from PyPDF2 import PdfFileReader
from nltk.corpus import words
words = words.words()
document_file = PdfFileReader(open(document_path, 'rb'))
num_pages = document_file.getNumPages()
for page_num in range(0, num_pages):
    page = document_file.getPage(page_num)
    page_contents = page.extractText()
    if set(page_contents.lower().split()).intersection(words):
        # process page_contents

最新更新