【问题标题】:Memory problems when using lapply for corpus creation使用 lapply 创建语料库时的内存问题
【发布时间】:2021-08-21 17:21:11
【问题描述】:

我的最终目标是将数千个 pdf 转换为语料库/文档术语矩阵以进行一些主题建模。我正在使用 pdftools 包来导入我的 pdf,并使用 tm 包来准备我的数据以进行文本挖掘。我设法导入和转换一个单独的 pdf,如下所示:

txt <- pdf_text("pdfexample.pdf")

#create corpus
txt_corpus <- Corpus(VectorSource(txt))

# Some basic text prep, with tm_map(), like:
txt_corpus <- tm_map(txt_corpus, tolower)

# create document term matrix
dtm <- DocumentTermMatrix(txt_corpus)

但是,我完全坚持自动化这个过程,而且我对循环或应用函数的经验有限。在将原始 pdf_text() 输出转换为语料库时,我的方法遇到了内存问题,即使我仅使用 5 个 pdf 文件(总计:1.5MB)测试了我的代码。 R 试图分配超过一半 GB 的向量。这对我来说似乎绝对不正确。我的尝试如下所示:

# Create a list of all pdf paths
file_list <- list.files(path = "mydirectory",
                 full.names = TRUE,
                 pattern = "name*", # to import only specific pdfs
                 ignore.case = FALSE)

# Run a function that reads the pdf of each of those files:
all_files <- lapply(file_list, FUN = function(files) {
             pdf_text(files)
             })

all_files_corpus = lapply(all_files,
                          FUN = Corpus(DirSource())) # That's where I run into memory issues

我在做一些根本错误的事情吗?不确定这是否只是一个内存问题,或者是否有更简单的方法来解决我的问题。至少,从我收集的信息来看, lapply 应该比循环更有效。但也许还有更多。我已经尝试自己解决了几天,但没有任何效果。

感谢任何关于如何进行的建议/提示!

编辑:我尝试只用一个 pdf 执行 lapply 并且我的 R 再次崩溃,即使我根本没有容量问题,当使用首先提到的代码时。

【问题讨论】:

    标签: r memory lapply text-mining corpus


    【解决方案1】:

    您可以编写一个函数,其中包含要在每个 pdf 上执行的一系列步骤。

    pdf_to_dtm <- function(file) {
      txt <- pdf_text(file)
      #create corpus
      txt_corpus <- Corpus(VectorSource(txt))
      # Some basic text prep, with tm_map(), like:
      txt_corpus <- tm_map(txt_corpus, tolower)
      # create document term matrix
      dtm <- DocumentTermMatrix(txt_corpus)
      dtm
    }
    

    使用lapply对每个文件应用函数

    file_list <- list.files(path = "mydirectory",
                     full.names = TRUE,
                     pattern = "name*", # to import only specific pdfs
                     ignore.case = FALSE)
    
    all_files_corpus <- lapply(file_list, pdf_to_dtm)
    

    【讨论】:

    • 非常感谢!这行得通!为什么这消耗的内存比我最初尝试的要少?
    • 我不知道DirSource() 做了什么,但lapply(all_files,FUN = Corpus(DirSource()) 似乎不对。因此,我将其更改为单独的功能。
    猜你喜欢
    • 2011-05-15
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    相关资源
    最近更新 更多