如何检测使用 PyPDF2.extractText 成功提取 pdf 文本的时间?
How do I detect when a pdf's text was successfully extracted with PyPDF2.extractText?
我正在使用 PyPDF2 库通过其 extractText
功能从 PDF 文件中提取文本,对于大多数 PDF,它工作得很好!
但是,某些 PDF 生成的文本如下所示:
\n!"#$%&'()"+,"-.".)/"0$-1"2)+3-$.45\n""!"#$%&'()#'+),$!"#-.#$-/[=14=].1+"#+12$\n!"#"$!%"&#"%$'$()%+,-$(%.($#"$(%"&#%/%0!%\n[=14=]"&$(%1(0,%3(%0"%0!%"&$%1(34+5"%36%1(0,$!7\n%%8%!"#$%&'($)%"\n%0!%#%+,-$(%"&#"%0!%3*9)%40'0!0-9$%-)%/%#*4%0"!7\n%%:%0!%"&$%3*9)%$'$%\n1(0,$%+,-$(7\n%%;3%099+!"(#"$%6+4#,$"#9%"&($,%36%#(0"&,$"052%<%90!"%-=%"&$%1(0,$%6#5"3(0>#"03*%\n36%+,-$(!%-$"=$$%/%#4%:?7%@(0,$%+,-$(!%#($%0*%\n6.'78"AB%,$#*!%,+9"019)7C\n%"/D%E[=14=]"&$(%1(0,$%*3(%53,13!0"%\n%:D%9%%%%%%%/FD%:BG\n%HD%:%%%%%%%/?D%HB?\n%%FD%:B:\n%3(
根据 the docs,这是意料之中的:
This works well for some PDF files, but poorly for others, depending
on the generator used.
不幸的是,extractText()
函数在输出上述文本时不会引发任何异常。
所以,我的问题是,有没有办法以编程方式检测 extractText()
函数何时出现 returns 乱码?
基于,这是解决方案。
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
我正在使用 PyPDF2 库通过其 extractText
功能从 PDF 文件中提取文本,对于大多数 PDF,它工作得很好!
但是,某些 PDF 生成的文本如下所示:
\n!"#$%&'()"+,"-.".)/"0$-1"2)+3-$.45\n""!"#$%&'()#'+),$!"#-.#$-/[=14=].1+"#+12$\n!"#"$!%"&#"%$'$()%+,-$(%.($#"$(%"&#%/%0!%\n[=14=]"&$(%1(0,%3(%0"%0!%"&$%1(34+5"%36%1(0,$!7\n%%8%!"#$%&'($)%"\n%0!%#%+,-$(%"&#"%0!%3*9)%40'0!0-9$%-)%/%#*4%0"!7\n%%:%0!%"&$%3*9)%$'$%\n1(0,$%+,-$(7\n%%;3%099+!"(#"$%6+4#,$"#9%"&($,%36%#(0"&,$"052%<%90!"%-=%"&$%1(0,$%6#5"3(0>#"03*%\n36%+,-$(!%-$"=$$%/%#4%:?7%@(0,$%+,-$(!%#($%0*%\n6.'78"AB%,$#*!%,+9"019)7C\n%"/D%E[=14=]"&$(%1(0,$%*3(%53,13!0"%\n%:D%9%%%%%%%/FD%:BG\n%HD%:%%%%%%%/?D%HB?\n%%FD%:B:\n%3(
根据 the docs,这是意料之中的:
This works well for some PDF files, but poorly for others, depending on the generator used.
不幸的是,extractText()
函数在输出上述文本时不会引发任何异常。
所以,我的问题是,有没有办法以编程方式检测 extractText()
函数何时出现 returns 乱码?
基于
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