使用R从双列PDF中提取文本

tso*_*kis 6 pdf r

我有很多PDF格式的双列格式.我正在使用pdftoolsR中的包.有没有办法按照两列格式读取每个PDF而不单独裁剪每个PDF?

每个PDF都包含可选文本,并且该pdf_text函数读取文本没有问题,唯一的问题是它将读取第一列的第一行,然后继续下一列,而不是向下移动第一列.

非常感谢您的帮助.

Fel*_*ago 8

我也有同样的问题.我所做的是为每个pdf页面获取最常用的空间值并将其存储到Vector中.然后我用它来切片.

library(pdftools)
src <- ""
trim <- function (x) gsub("^\\s+|\\s+$", "", x)

QTD_COLUMNS <- 2
read_text <- function(text) {
  result <- ''
  #Get all index of " " from page.
  lstops <- gregexpr(pattern =" ",text)
  #Puts the index of the most frequents ' ' in a vector.
  stops <- as.integer(names(sort(table(unlist(lstops)),decreasing=TRUE)[1:2]))
  #Slice based in the specified number of colums (this can be improved)
  for(i in seq(1, QTD_COLUMNS, by=1))
  {
    temp_result <- sapply(text, function(x){
      start <- 1
      stop <-stops[i] 
      if(i > 1)            
        start <- stops[i-1] + 1
      if(i == QTD_COLUMNS)#last column, read until end.
        stop <- nchar(x)+1
      substr(x, start=start, stop=stop)
    }, USE.NAMES=FALSE)
    temp_result <- trim(temp_result)
    result <- append(result, temp_result)
  }
  result
}

txt <- pdf_text(src)
result <- ''
for (i in 1:length(txt)) { 
  page <- txt[i]
  t1 <- unlist(strsplit(page, "\n"))      
  maxSize <- max(nchar(t1))
  t1 <- paste0(t1,strrep(" ", maxSize-nchar(t1)))
  result = append(result,read_text(t1))
}
result
Run Code Online (Sandbox Code Playgroud)


小智 5

使用tabulizer::extract_text(file)函数有一种更简单的方法来做到这一点。

它适用于包含在单列中的 PDF 文本和包含在 2+ 列中的 PDF 文本。是的,就是这么简单!

  • 2021 年 12 月:CRAN 中不再提供 tabulizer。 (3认同)