尝试从包含 70 个 pdf 文件的目录中的每个 pdf 中提取部分页面

Trying to extract a subset of pages from each pdf in a directory with 70 pdf files

我正在使用 tidyverse、tidytext 和 pdftools。我想解析 70 个 pdf 文件目录中的单词。我正在使用这些工具成功地做到这一点,但下面的代码获取了所有页面而不是我想要的子集。我需要跳过前两页和 select 第 3 页到每个 pdf 文件的末尾。

directory <- "Student_Artifacts/"
pdfs <- paste(directory, "/", list.files(directory, pattern = "*.pdf"), sep = "")
pdf_names <- list.files(directory, pattern = "*.pdf")
pdfs_text <- map(pdfs, (pdf_text))
my_data <- data_frame(document = pdf_names, text = pdfs_text)

我发现通过像这样将 [3:12] 放在括号中我可以获取第 3-12 个文件:

pdfs_text <- map(pdfs, (pdf_text))[3:12]

但这不是我想要的。如何使用 [3:12] 规范从每个 pdf 文件中提取我想要的页面?

首先,您可以在 pdf_text 的映射中索引每个 PDF 的第 3 到第 12 页,只需进行一些非常小的更改:

pdfs_text <- map(pdfs, ~ pdf_text(.x)[3:12])

但这假设您所有的 70 个 PDF 都是 13 页。这也可能很慢,特别是如果其中一些真的很大。尝试这样的事情(我使用 R 的 PDF 文档进行演示):

library(furrr)
#> Loading required package: future
library(pdftools)
library(tidyverse)
library(magrittr)
#> 
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#> 
#>     set_names
#> The following object is masked from 'package:tidyr':
#> 
#>     extract

plan(multiprocess)

directory <- file.path(R.home("doc"), "manual")
pdf_names <- list.files(directory, pattern = "\.pdf$", full.names = TRUE)
# Drop the full reference manual since it's so big
pdf_names %<>% str_subset("fullrefman.pdf", negate = TRUE)
pdfs_text <- future_map(pdf_names, pdf_text, .progress = TRUE)
#> Progress: ----------------------------------------------------------------------------------- 100%

my_data   <- tibble(
  document = basename(pdf_names), 
  text     = map_chr(pdfs_text, ~ {
    str_c("Page ", seq_along(.x), ": ", str_squish(.x)) %>% 
      tail(-2) %>% 
      str_c(collapse = "; ")
  })
)

my_data
#> # A tibble: 6 x 2
#>   document    text                                                         
#>   <chr>       <chr>                                                        
#> 1 R-admin.pdf "Page 3: i Table of Contents 1 Obtaining R . . . . . . . . .~
#> 2 R-data.pdf  "Page 3: i Table of Contents Acknowledgements . . . . . . . ~
#> 3 R-exts.pdf  "Page 3: i Table of Contents Acknowledgements . . . . . . . ~
#> 4 R-intro.pdf "Page 3: i Table of Contents Preface . . . . . . . . . . . .~
#> 5 R-ints.pdf  "Page 3: i Table of Contents 1 R Internal Structures . . . .~
#> 6 R-lang.pdf  "Page 3: i Table of Contents 1 Introduction . . . . . . . . ~

reprex package (v0.3.0)

于 2019-10-19 创建

要点:

  1. tail(-2) 正在做您最关心的工作:删除前两页。通常您使用 tail() 来抓取最后 n 页,但它也非常适合抓取除前 n 页以外的所有页面 - 只需使用底片。
  2. plan()future_map() 并行化 PDF 阅读,每个虚拟核心一次阅读一个 PDF。还有进度条!
  3. 我在这里 text 的构造中进行了一些奇特的字符串连接,因为看起来您最终希望在最终 table 的一个单元格中包含每个文档页面的全文。我在每个页面的文本之间插入“; Page [n]:”,这样数据就不会丢失,而且我还删除了所有文本中多余的空格,因为通常有很多。