在循环中使用pdftools时的错误处理

问题描述

我正在尝试从多个pdf文件中提取某些表格,但并非所有文件都具有该表格。 即使第一个文件不包含特定表,如何使用trycatch或类似方法跳过并继续下一个文件?

library(pdftools)
library(tidyverse)

url <- c("https://www.computershare.com/News/Annual%20Report%202019.pdf?2","https://www.annualreports.com/HostedData/AnnualReportArchive/a/LSE_ASOS_2018.PDF")

raw_text <- map(url,pdf_text)

clean_table1 <- function(raw) {
  
  raw <- map(raw,~ str_split(.x,"\\n") %>% unlist())
  raw <- reduce(raw,c)
  
  table_start <- stringr::str_which(tolower(raw),"twenty largest shareholders")
  table_end <- stringr::str_which(tolower(raw),"total")
  table_end <- table_end[min(which(table_end > table_start))]
  
  table <- raw[(table_start + 3 ):(table_start + 25)]
  table <- str_replace_all(table,"\\s{2,}","|")
  text_con <- textConnection(table)
  data_table <- read.csv(text_con,sep = "|")
  #colnames(data_table) <- c("Name","Number of Shares","Percentage")
  data_table
}

shares <- map_df(raw_text,clean_table1) 

尝试运行时出现以下错误。

Error in (table_start + 3):(table_start + 25) : argument of length 0
In addition: Warning message:
In min(which(table_end > table_start)) :
  no non-missing arguments to min; returning Inf

解决方法

您可以检查lengthtable_start return中的NULL是否为0,因此在使用map_df时,这些记录将自动折叠并且您将一个组合的数据框。

library(tidyverse)

clean_table1 <- function(raw) {
  
  raw <- map(raw,~ str_split(.x,"\\n") %>% unlist())
  raw <- reduce(raw,c)
  
  table_start <- stringr::str_which(tolower(raw),"twenty largest shareholders")
  if(!length(table_start)) return(NULL)
  table_end <- stringr::str_which(tolower(raw),"total")
  table_end <- table_end[min(which(table_end > table_start))]
  
  table <- raw[(table_start + 3 ):(table_start + 25)]
  table <- str_replace_all(table,"\\s{2,}","|")
  text_con <- textConnection(table)
  data_table <- read.csv(text_con,sep = "|")
  #colnames(data_table) <- c("Name","Number of Shares","Percentage")
  data_table
}

shares <- map_df(raw_text,clean_table1)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...