2017-09-30 56 views
0

我正在將1000個pdf轉換爲文本進行數據分析。我正在使用包pdftools。使用pdftools將pdf的批量轉換爲文本

我已經能夠使用下面的代碼轉換成2 PDF:

library(pdftools) 
file_list <- list.files('pdf', full.names = TRUE, pattern = 'pdf') 

for(i in 1:length(file_list)){ 
    temp <- pdf_text(file_list[i]) 
    temp <- tolower(temp) 

    file_name = paste(file_list[i], '.txt') 
    sink(file_name) 
    cat(temp) 
    sink() 

} 

,但是當我增加超過2我收到以下錯誤:

" Error in poppler_pdf_text(loadfile(pdf), opw, upw) : PDF parsing failure." 

還,我想最終的文本文件只有「file_name.txt」現在我得到「file_name.pdf .txt」

謝謝,

回答

0
library(pdftools) 
library(purrr) 

setwd("/tmp/test") 

file_list <- list.files(".", full.names = TRUE, pattern = '.pdf$') 

s_pdf_text <- safely(pdf_text) # helps catch errors 

walk(file_list, ~{          # iterate over the files 

    res <- s_pdf_text(.x)        # try to read it in 
    if (!is.null(res$result)) {       # if successful 

    message(sprintf("Processing [%s]", .x)) 

    txt_file <- sprintf("%stxt", sub("pdf$", "", .x)) # make a new filename 

    unlist(res$result) %>%        # cld be > 1 pg (which makes a list) 
     tolower() %>%          
     paste0(collapse="\n") %>%      # make one big text block with line breaks 
     cat(file=txt_file)        # write it out 

    } else {            # if not successful 
    message(sprintf("Failure converting [%s]", .x)) # show a message 
    } 

}) 
+0

Thanks @ hrbrmstr!但是,我能夠在1000 pdf中只轉換20個。我已經嘗試使用另一個代碼(見下文),但是使用該代碼的txt。我得到的文件是腐敗的字符(我所有的文件都是西班牙文的,所以我有多個特殊字符'',í,ó,ú',我需要所有字符都是小寫字母) – Claudia

+0

pdf_files < - list.files (path = paste(getwd(),'/ pdf',sep ='') if在pdf_files中){ 系統( paste( paste(''',getwd(),'/xpdf/bin64/pdftotext.exe'',sep =''), paste0(''',',',' ')), wait = FALSE) } } cat('\ n轉換爲文本完成。\ n \ n') – Claudia

+0

Unfortun好吧,人們不可能爲你編寫代碼。 'stringi'包中有'stri_trans_tolower()',它可以幫助翻譯不同的字符集。 – hrbrmstr