python - 如何使用 PDFminer 避免密码错误的 PDF 文件
问题描述
我想从我的计算机中收集所有 PDF 文件并从每个文件中提取文本。我目前拥有的两个功能都是这样做的,但是,一些 PDF 文件给了我这个错误:
raise PDFPasswordIncorrect
pdfminer.pdfdocument.PDFPasswordIncorrect
我在打开和读取 PDF 文件的函数中提出了错误,这似乎在忽略错误方面起作用,但现在它忽略了所有 PDF 文件,包括以前不是问题的好文件。
我怎样才能让它只忽略给我这个错误的PDF文件而不是每个PDF?
def pdfparser(x):
try:
raise PDFPasswordIncorrect(pdfminer.pdfdocument.PDFPasswordIncorrect)
fp = open(x, 'rb')
rsrcmgr = PDFResourceManager()
retstr = io.StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
except (RuntimeError, TypeError, NameError,ValueError,IOError,IndexError,PermissionError):
print("Error processing {}".format(name))
for page in PDFPage.get_pages(fp):
interpreter.process_page(page)
data = retstr.getvalue()
return(data)
def pdfs(files):
for name in files:
try:
IP_list = (pdfparser(name))
keyword = re.findall(inp,IP_list)
file_dict['keyword'].append(keyword)
file_dict['name'].append(name.name[0:])
file_dict['created'].append(time.ctime(name.stat().st_ctime))
file_dict['modified'].append(time.ctime(name.stat().st_mtime))
file_dict['path'].append(name)
file_dict["content"].append(IP_list)
except (RuntimeError, TypeError, NameError,ValueError,IOError,IndexError,PermissionError):
print("Error processing {}".format(name))
#print(file_dict)
return(file_dict)
pdfs(files)
解决方案
如果您打开受密码保护的 Pdf,如果您不提供正确的密码,为什么要手动引发错误?
您的代码每次都会引发此错误!
相反,如果发生错误,您需要捕获并跳过该文件。请参阅更正的代码:
def pdfparser(x):
try:
# try to open your pdf here - do not raise the error yourself!
# if it happens, catch and handle it as well
except PDFPasswordIncorrect as e: # catch PDFPasswordIncorrect
print("Error processing {}: {}".format(name,e)) # with all other errors
# no sense in doing anything if you got an error until here
return None
# do something with your pdf and collect data
data = []
return(data)
def pdfs(files):
for name in files:
try:
IP_list = pdfparser(name)
if IP_list is None: # unable to read for whatever reasons
continue # process next file
# do stuff with your data if you got some
# most of these errors are already handled inside pdfparser
except (RuntimeError, TypeError, NameError,ValueError,
IOError,IndexError,PermissionError):
print("Error processing {}".format(name))
return(file_dict)
pdfs(files)
第二个try/catch:
可以def pdfs(files):
缩小,所有与文件相关的错误都发生在里面def pdfparser(x):
并在那里处理。您的其余代码不完整,并且引用了我不知道的内容:
file_dict inp name # used as filehandle for .stat() but is a string etc
推荐阅读
- react-native - 为 React Native 选择器设置样式以与文本输入对齐
- visual-studio - 使用 Visual Studio 2017 在单独的 chrome 窗口上打开多个 Web/Api 项目
- json - 如何解决使用 parse 引起的 JSON Injection 漏洞
- javascript - 从文件加载 XML 并解析?
- c# - 从 Web 服务接收 C# 中的数据
- c# - 使用 EF Core 和内存数据库进行单元测试
- jsf - JSF websocket 更新 viewScope
- java - 如何在我的自定义布局(VBox、HBox 等)元素中获取用 fxml 编写的所有子标签
- react-redux - 根据 first 的响应在 redux observables 中对 ajax 请求进行排序,并单独处理错误和调度动作
- regex - 我想知道满足以下模式的正则表达式: