按页而不是段落提取word文档的文本(R)

问题描述 投票:0回答:1

我目前在(数百个).pdf 和 .docx 文件中有(大量)文本数据。我想在稍后的分析中提取每页的文本,页码变得相关。

对于 pdf 文件,我使用的是 pdftools 包,它工作得很好并返回一个带有字符串的向量,其中每个元素都是文档一页的文本。 跨越两页的句子或单词可能会被截断,但现在这不是什么大问题。

pdftools::pdf_text("Test.pdf") # delivers a string voor each page

对于word文档,我希望有相同的输出。我目前正在为此尝试 officer 包。但是,这个包读取每段而不是每页的文本。

# load the file
doc <- officer::read_docx(path = "Test.docx")
# extract the text
doc_text <- officer::docx_summary(doc)$text # delivers a string for each paragraph

有什么办法可以将返回段落的输出更改为返回页面? 如果有必要,通过调整底层的 read_docx 或 docx_summary 函数来为每个分页符而不是每个段落拆分文本?

此外,欢迎推荐其他包或方法来实现输出。 但是,如果可能的话,我会避免将 word 文档转换为 pdf 文档。

可以使用 Lorem Ipsum 生成器生成一个简单的测试文档: https://www.lipsum.com/feed/html

r text-parsing officer pdf-scraping
1个回答
0
投票

我已经能够使用以下代码提取特定页面的文本:

library(RDCOMClient)

wordApp <- COMCreate("Word.Application")
wordApp[["Visible"]] <- TRUE
wordApp[["DisplayAlerts"]] <- FALSE
path_To_Word_File <- "D:\\Word_File.docx"
doc <- wordApp[["Documents"]]$Open(normalizePath(path_To_Word_File), ConfirmConversions = FALSE)
doc_Selection <-  wordApp$Selection()

list_Text <- list()

for(i in 1 : 40)
{
  print(i)
  error_Term <- tryCatch(wordApp[["ActiveDocument"]]$ActiveWindow()$Panes(1)$Pages(1)$Rectangles(i)$Range()$Select(),
                         error = function(e) NA)
  
  list_Text[[i]] <- tryCatch(doc_Selection$Range()$Text(), error = function(e) NA)
  
  if(!is.null(error_Term))
  {
    break
  }
}

list_Text

想法是我们遍历页面的所有矩形并提取所有矩形的文本。

© www.soinside.com 2019 - 2024. All rights reserved.