首页 > 解决方案 > 为什么 pdftools 中的 pdf_text 只读取我的 pdf 列表中每个 pdf 元素的第一页?

问题描述

我想创建一个数据框,其中包含我的 pdf 列表中 ech pdf 的所有文本和标题。我制作了一个 for 循环,但是当我打开生成的数据框时,我发现并非每个 pdf 中的所有文本都已处理为文本,而只有最后一页。

这里的代码:

#folder
folder <- paste0(getwd(), "/data/pdfs/")

#QC
qc <- sample(1:length(pdf_list), size = 1, replace = F)

#Create a vector of all the files in the folder selected
file_vector <- list.files(all.files = T, path = folder, recursive = T)

#Apply a filter to the file vector of files
pdf_list <- file_vector[grepl(".pdf", file_vector)]

#make the data frame
corpus_raw <- data.frame("title" = c(),"text" = c())

#list of pdf files comprehensive of path
files <- paste0(folder,pdf_list)

#cycle for the text fetching: 
for (i in 1:length(pdf_list)){
    #print i so that I know the loop is working right
    print(i)
    #take the text
    text_from_pdf <- pdf_text(pdf = files[i])
    temp_store_data <- data.frame("title" = gsub(pattern = "\\d\\/", replacement = "", 
                                               x = pdf_list[i], ignore.case = T), 
                                  "text" = text_from_pdf, stringsAsFactors = F)
    # quality control
    if (i == qc[1]){
      print(temp_store_data[i,2])
      write(temp_store_data[i,2], "data/quality_control.txt")
    }
    colnames(temp_store_data) <- c("title", "text")
    corpus_raw <- rbind(corpus_raw, temp_store_data)
}

你能帮我解决这个问题吗?谢谢!

标签: rfor-looppdfpdftools

解决方案


pdf_text创建一个每页一个字符串的向量,而不是单个文本字符串。您只是将列表的第 i 页写入 qc 文本文件。

您可以在阅读 pdf 时尝试此操作:

text_from_pdf <- paste(pdf_text(pdf = files[i]), collapse = "\n")

如果您没有整本小说作为 pdf 格式存储,这应该可以工作。


推荐阅读