2017-10-09 58 views
0

我在每個包含2個pdf的主文件夾中有3000個子文件夾。 我寫了下面的代碼來轉換文本文件中的PDF。PDF到文本文件的轉換

* all.subfolders < - list.dirs( 「#路徑主文件夾」,full.names = TRUE)

sapply(all.subfolders[-1], function(x) { 

file <-list.files(x, full.names=TRUE) 

lapply(file, function(x) system(paste('"C:\\Program Files (x86)\\xpdfbin-win-3.03\\bin64\\pdftotext.exe"', paste0('"', x, '"')), wait = FALSE))})* 

但在幾個PDF文件可能無法在文本轉換,如何讓他們在一個列表左右。 請幫忙。

+0

爲什麼不能轉換這些pdf?你收到錯誤信息了嗎?也許這些PDF文件不包含文本? –

+0

它們包含文本,但我認爲PDF是掃描的文件,因此無法轉換。我dint得到任何錯誤消息。執行命令後,我發現他們轉換的文件在各自的文件夾中。 –

回答

0

我的聲望不夠高,無法評論,所以請原諒我作出回答,但事實並非如此。您的PDF文件可能受到保護,因此無法提取文本。使用pdf查看器打開文檔時,請嘗試從這些文檔中複製文本。這可能由於保護而不起作用。如果您有權限提取和處理文本,則可以考慮將文件轉換爲圖像(例如,通過ImageMagick),並在圖像上應用OCR(例如,通過tesseract)。要開始您可能會參考,例如,以下腳本https://gist.github.com/benmarwick/11333467

爲了迴應您關於如何識別尚未轉換的文件的評論,您可以使用以下方法。我希望這是你一直在尋找的東西。

#retrieve all file paths 
#note that you can use recursive = T to avoid looping over directories yourself 
allfiles <- list.files("C:/.../mydirectory", full.names = T, recursive = T) 

#split filepaths into a set of pdf and txt files 
#txt files will, of course, only be the files that have been converted 
pdffiles <- allfiles[grep("pdf$", allfiles)] 
txtfiles <- allfiles[grep("txt$", allfiles)] 

#remove file ending 
pdffiles <- gsub(".pdf", "", pdffiles) 
pdffiles <- gsub(".txt", "", pdffiles) 

#check which files have not been converted 
notconverted <- setdiff(pdffiles, txtfiles) 

#if needed, file ending can be added again 
#e.g. for copying the unconverted files into a separate directory or so 
notconverted <- paste0(pdffiles, ".pdf") 
+0

直接的問題是找到那些未轉換的PDF /子文件夾...我有3000個子文件夾,因此手動無法檢查每個文件夾。 –

+0

非常感謝您的時間和代碼。它解決了查找未轉換文件的問題。謝謝 –

+0

我很高興能幫上忙。請考慮接受關閉此主題的答案。 –