首页 > 解决方案 > 将 png 文件转换为 txt 文件

问题描述

我有 100 个扫描的 PDF 文件,我需要将它们转换为文本文件。

我首先将它们转换为 png 文件(参见下面的脚本),现在我需要帮助将这 100 个 png 文件转换为 100 个文本文件。

library(pdftools)
library("tesseract")

#location
dest <- "P:\\TEST\\images to text"

#making loop for all files
myfiles <- list.files(path = dest, pattern = "pdf",  full.names = TRUE)

#Convert files to png
sapply(myfiles, function(x)
  pdf_convert(x, format = "png", pages = NULL, 
              filenames = NULL, dpi = 600, opw = "", upw = "", verbose = TRUE))

#read files
cat(text)

我希望每个 png 文件都有一个文本文件:

来自:file1.png、file2.png、file3.png...

到:file1.txt、file2.txt、file3.txt...

但实际结果是一个包含所有 png 文件文本的文本文件。

标签: rpdf

解决方案


我猜你用 teh png -> textbit 省略了这个 bit,但我假设你使用了library(tesseract).

您可以在代码中执行以下操作:

library(tesseract)
eng <- tesseract("eng")
sapply(myfiles, function(x) {
  png_file <- gsub("\\.pdf", ".png", x)
  txt_file <- gsub("\\.pdf", ".txt", x)
  pdf_convert(x, format = "png", pages = 1, 
              filenames = png_file, dpi = 600, verbose = TRUE)

  text <- ocr(png_file, engine = eng)
  cat(text, file = txt_file)
  ## just return the text string for convenience
  ## we are anyways more interested in the side effects
  text
})

推荐阅读