首页 文章

使用R识别PDF表

提问于
浏览
12

我正在尝试从一些pdf报告中的表中提取数据 .

我已经看到一些使用pdftools和类似软件包的例子我成功获取了文本,但是,我只想提取表格 .

有没有办法使用R来识别和提取表格?

2 回答

  • 3

    Awsome的问题,我最近想知道同样的事情,谢谢!

    我做了它, tabulizer 正如@hrbrmstr所暗示的那样 . 如果您使用的是R版3.5.1,我将提供以下解决方案 . 按特定顺序安装三个包:

    install.packages("rJava")
    library(rJava) # load and attach 'rJava' now
    install.packages("devtools")
    devtools::install_github("ropensci/tabulizer", args="--no-multiarch")
    

    现在,您已准备好从PDF报告中提取表格 .

    library(tabulizer)
    
    # specify an example and load it into your workspace
    report <- "http://www.stat.ufl.edu/~athienit/Tables/Ztable.pdf" 
    lst <- extract_tables(report, encoding="UTF-8") 
    # peep into the doc for further specs (page, location etc.)!
    
    # after examing the list you want to do some tidying
    # 1st delete blank columns
    lst[[1]] <- lst[[1]][, -3]
    lst[[2]] <- lst[[2]][, -4]
    
    # 2nd bind the list elements, if you want and create a df...
    table <- do.call(rbind, lst)
    table <- as.data.frame(table[c(2:37, 40:nrow(table)), ],
                           stringsAsFactors=FALSE) # ...w/o obsolete rows
    
    # 3rd take over colnames, cache rownames to vector
    colnames(table) <- table[1, ]
    rn <- table[2:71, 1]
    table <- table[-1,-1] # and bounce them out of the table
    
    # 4th I'm sure you want coerce to numeric 
    table <- as.data.frame(apply(table[1:70,1:10], 2, 
                                 function(x) as.numeric(as.character(x))))
    rownames(table) <- rn # bring back rownames 
    
    table # voilà
    

    希望对你有效 .

    Limitations: 当然这个例子中的表非常简单,也许你不得不乱用 gsubstringr tidyr 和这种东西 .

  • 10

    我也想知道答案 . 但根据我的经验,您需要使用正则表达式以您想要的格式获取数据 . 您可以看到以下示例:

    library(pdftools)
    dat <- pdftools::pdf_text("https://s3-eu-central-1.amazonaws.com/de-hrzg-khl/kh-ffe/public/artikel-pdfs/Free_PDF/BF_LISTE_20016.pdf")
    dat <- paste0(dat, collapse = " ")
    pattern <- "Berufsfeuerwehr\\s+Straße(.)*02366.39258"
    extract <- regmatches(dat, regexpr(pattern, dat))
    extract <- gsub('\n', "  ", extract)
    strsplit(extract, "\\s{2,}")
    

    然后,可以从这里循环数据以根据需要创建表 . 但正如您在链接中看到的那样,PDF不仅仅是一个表格 .

相关问题