【发布时间】:2021-07-31 04:26:58
【问题描述】:
我正在使用 R 中的“tesseract”库将“PDF 文件转换为文本”,如下所示:https://cran.r-project.org/web/packages/tesseract/vignettes/intro.html
library(pdftools)
library(tesseract)
pngfile <- pdftools::pdf_convert('myfile_1.pdf', dpi = 600)
text <- tesseract::ocr(pngfile)
cat(text)
上面的代码完美运行。现在,我正在尝试“大量上传”大量 PDF 文件并将它们转换为文本 - 目前,我想出了如何手动执行此操作
#import and convert 1st file
pngfile_1 <- pdftools::pdf_convert('myfile_1.pdf', dpi = 600)
text_1 <- tesseract::ocr(pngfile_1)
#import and convert 2nd file (note: the files do not have the same naming convention)
pngfile_2 <- pdftools::pdf_convert('second_file.pdf', dpi = 600)
text_2 <- tesseract::ocr(pngfile_2)
etc
我将上面的代码复制/粘贴了 50 次(同时更改了“索引”,即pngfile_i, text_i)并且能够完成我想做的事情。但是,我正在寻找一种“自动”的方式来导入和转换所有 pdf 文件。
目前,我所有的 pdf 文件都在以下文件夹中:
"C:/Users/me/Documents/mypdfs"
我发现以下代码可用于将 pdf 文件“大量导入”到 R 中:
library(dplyr)
library(data.table)
tbl_fread <-
list.files(pattern = "*.pdf") %>%
map_df(~fread(.))
但我不确定如何指示此代码从正确的目录 ("C:/Users/me/Documents/mypdfs") 导入所有 pdf。我也不知道如何指示 R 将每个导入的 pdf “重命名”为“pdf_1、pdf_2 等”。
如果所有 pdf 文件都正确导入和创建,我可以编写一个“循环”并执行所需的命令,例如
# "n" would be the total number of pdf files
for (i in 1:n)
{
pngfile_i <- pdftools::pdf_convert('myfile_i.pdf', dpi = 600)
text_i <- tesseract::ocr(pngfile_i)
}
有人可以告诉我怎么做吗?
谢谢
【问题讨论】:
-
这个问题有答案了吗?