如何检查PDF是扫描图像还是包含R中的文本
How to check if PDF is scanned image or contains text in R
我正在 R 中对几个 PDF (>1000) 进行结构方程模型
但是,有些 PDF 是可读的,而另一些是扫描的,即我需要 运行 通过 OCR 功能对它们进行扫描。
因此,我需要找到一种方法来自动识别哪些 PDF 包含文本,哪些不包含文本。具体来说,我希望通过 OCR 找到 return 给定 PDF 是否应该 运行 的方法。
有没有人知道 R 中的任何函数或包可能有助于做到这一点 - 我可以找到几个 Python 的解决方案,但无法在 R 中找到一些解决方案。
你可以使用这样的方法(@danlooo 已经建议但我想把它拼出来):
files <- list.files("/home/johannes/pdfs/",
pattern = ".pdf$",
full.names = TRUE)
pdfs_l <- lapply(files, function(f) {
out <- pdftools::pdf_text(f)
# I set the test to an arbitrary number of characters, it works for me but you want
# to maybe fine tune it a bit
contains_text <- nchar(out) > 15
if (!contains_text) {
out <- pdftools::pdf_ocr_text(f)
}
data.frame(text = out, ocr = !contains_text)
})
pdfs_l |>
dplyr::bind_rows() |>
dplyr::mutate(text = trimws(text)) |>
tibble::as_tibble()
#> # A tibble: 22 × 2
#> text ocr
#> <chr> <lgl>
#> 1 "TEAM MEMBERS:\n … FALSE
#> 2 "WS 21/22 … FALSE
#> 3 "WS 21/22 … FALSE
#> 4 "TEAM MEMBERS:\n … FALSE
#> 5 "TEAM MEMBERS:\n … FALSE
#> 6 "Key Concepts in Political Communication\n @Agenda Setting, Priming… FALSE
#> 7 "Key Concepts in Political Communication\n @Agenda Setting, Priming… FALSE
#> 8 "ELECTIONS AND CAMPAIGNS\n … FALSE
#> 9 "" TRUE
#> 10 "" TRUE
#> # … with 12 more rows
由 reprex package (v2.0.1)
创建于 2022-02-10
我正在 R 中对几个 PDF (>1000) 进行结构方程模型
但是,有些 PDF 是可读的,而另一些是扫描的,即我需要 运行 通过 OCR 功能对它们进行扫描。
因此,我需要找到一种方法来自动识别哪些 PDF 包含文本,哪些不包含文本。具体来说,我希望通过 OCR 找到 return 给定 PDF 是否应该 运行 的方法。
有没有人知道 R 中的任何函数或包可能有助于做到这一点 - 我可以找到几个 Python 的解决方案,但无法在 R 中找到一些解决方案。
你可以使用这样的方法(@danlooo 已经建议但我想把它拼出来):
files <- list.files("/home/johannes/pdfs/",
pattern = ".pdf$",
full.names = TRUE)
pdfs_l <- lapply(files, function(f) {
out <- pdftools::pdf_text(f)
# I set the test to an arbitrary number of characters, it works for me but you want
# to maybe fine tune it a bit
contains_text <- nchar(out) > 15
if (!contains_text) {
out <- pdftools::pdf_ocr_text(f)
}
data.frame(text = out, ocr = !contains_text)
})
pdfs_l |>
dplyr::bind_rows() |>
dplyr::mutate(text = trimws(text)) |>
tibble::as_tibble()
#> # A tibble: 22 × 2
#> text ocr
#> <chr> <lgl>
#> 1 "TEAM MEMBERS:\n … FALSE
#> 2 "WS 21/22 … FALSE
#> 3 "WS 21/22 … FALSE
#> 4 "TEAM MEMBERS:\n … FALSE
#> 5 "TEAM MEMBERS:\n … FALSE
#> 6 "Key Concepts in Political Communication\n @Agenda Setting, Priming… FALSE
#> 7 "Key Concepts in Political Communication\n @Agenda Setting, Priming… FALSE
#> 8 "ELECTIONS AND CAMPAIGNS\n … FALSE
#> 9 "" TRUE
#> 10 "" TRUE
#> # … with 12 more rows
由 reprex package (v2.0.1)
创建于 2022-02-10