我正在一个项目中,将PDF扫描将打字机写的《战争日记》笔记转换为文本。我可以成功提取(可能是90%的原始未调整大小的文件)提取主文本,然后我首先进行裁剪。
Reprex数据:您可以从图片开始或从下面提供的文字开始尝试。
我的挑战是保持文本的“每日”结构,该结构每天有7个段落或节,并且用“ \ n”或“ \ n \ n”进行拆分并不完全正确。
我正在为项目使用pdftools / stringr / tesseract / magick的组合:
library(tesseract)
library(dplyr)
library(stringr)
library(pdftools)
library(readr)
library(magick)
Run Code Online (Sandbox Code Playgroud)
使用方法:
image <- image_read("./test-data/page_1.png") #change to your path
text -> image %>%
image_crop(geometry_area(width = 1220, height = 900,
y_off = 260, x_off = 355)) %>%
image_resize("2000x") %>%
image_convert(type = 'Grayscale') %>%
image_trim(fuzz = 40) %>%
image_write(format = 'png', density = '300x300') %>%
tesseract::ocr()
Run Code Online (Sandbox Code Playgroud)
给出一个字符串:
[1] "Weather clear all day. A smaii arms inspection hela at i400 hrs. A …Run Code Online (Sandbox Code Playgroud) 最终目标是使用 pdftools 包有效地浏览一千页 pdf 文档,以一致、安全地生成可用的数据框/标题。我尝试使用 tabulizer 包和 pdf_text 函数,但结果不一致。因此,开始研究pdf_data()我更喜欢的功能。
对于那些不熟悉 pdf_data 函数的人来说,它将 pdf 页面转换为坐标网格,0,0 坐标位于页面的左上角。因此,通过排列 x,y 坐标,然后将文档旋转为宽格式,所有信息都会像在页面上一样显示,只有 NA 表示空白
这是一个使用熟悉的 mtcars 数据集的简单示例。
library(pdftools)
library(tidyverse)
library(janitor)
pdf_file <- "https://github.com/ropensci/tabulizer/raw/master/inst/examples/data.pdf"
mtcars_pdf_df <- pdf_data(pdf_file)[[1]]
mtcars_pdf_df%>%
arrange(x, y)%>%
pivot_wider(id_cols = y, names_from = x, values_from = text)%>%
unite(col = Car_type, `154`:`215`, sep = " ", remove = TRUE, na.rm = TRUE)%>%
arrange(y)%>%
rename("Page Number" = `303`)%>%
unite(col = mpg, `253`:`254`, sep = "", remove = TRUE, na.rm = TRUE)%>%
unite(col = cyl, …Run Code Online (Sandbox Code Playgroud)