R: tm文本挖掘包:文档级元数据生成速度较慢



我有一个要处理的文档列表,对于每一条记录,我都想将一些元数据附加到"语料库"数据结构中的文档"成员",该数据结构是R包tm(通过读取文本文件)生成的。

此for循环有效,但速度非常慢,性能似乎随着函数f~1/n_docs而下降。

for (i in seq(from= 1, to=length(corpus), by=1)){
    if(opts$options$verbose == TRUE || i %% 50 == 0){
        print(paste(i, " ", substr(corpus[[i]], 1, 140), sep = " "))
    }
    DublinCore(corpus[[i]], "title") = csv[[i,10]]  
    DublinCore(corpus[[i]], "Publisher" ) = csv[[i,16]]   #institutions
}       

这可能会对语料库变量产生影响,但我不知道是什么。但是,当我把它放在tm_map()(类似于lapply()函数)中时,它运行得更快,但更改并不是持久的:

i = 0
corpus = tm_map(corpus, function(x){
            i <<- i + 1

    if(opts$options$verbose == TRUE){
        print(paste(i, " ", substr(x, 1, 140), sep = " "))
    }
    meta(x, tag = "Heading") = csv[[i,10]]  
    meta(x, tag = "publisher" ) = csv[[i,16]] 
})

变量语料库在退出tm_map函数后具有空的元数据字段。它应该被填满。我还有一些其他的事情要做。

meta()函数的R文档是这样说的:

     Examples:
      data("crude")
      meta(crude[[1]])
      DublinCore(crude[[1]])
      meta(crude[[1]], tag = "Topics")
      meta(crude[[1]], tag = "Comment") <- "A short comment."
      meta(crude[[1]], tag = "Topics") <- NULL
      DublinCore(crude[[1]], tag = "creator") <- "Ano Nymous"
      DublinCore(crude[[1]], tag = "Format") <- "XML"
      DublinCore(crude[[1]])
      meta(crude[[1]])
      meta(crude)
      meta(crude, type = "corpus")
      meta(crude, "labels") <- 21:40
      meta(crude)

我尝试了许多这样的调用(使用var"corporate"而不是"rough"),但它们似乎不起作用。其他人似乎曾经对类似的数据集有过同样的问题(2009年的论坛帖子,没有回应)

这里有一些基准测试。。。

使用for循环:

expr.for <- function() {
  for (i in seq(from= 1, to=length(corpus), by=1)){
    DublinCore(corpus[[i]], "title") = LETTERS[round(runif(26))]
    DublinCore(corpus[[i]], "Publisher" ) = LETTERS[round(runif(26))]
  }
}
microbenchmark(expr.for())
# Unit: milliseconds
#         expr      min       lq   median       uq      max
# 1 expr.for() 21.50504 22.40111 23.56246 23.90446 70.12398

tm_map:

corpus <- crude
expr.map <- function() {
  tm_map(corpus, function(x) {
    meta(x, "title") = LETTERS[round(runif(26))]
    meta(x, "Publisher" ) = LETTERS[round(runif(26))]
    x
  })
}
microbenchmark(expr.map())
# Unit: milliseconds
#         expr      min       lq   median       uq      max
# 1 expr.map() 5.575842 5.700616 5.796284 5.886589 8.753482

因此,正如您所注意到的,tm_map版本似乎快了4倍。

在您的问题中,您说tm_map版本中的更改不是持久的,这是因为您在匿名函数结束时没有返回x。最终应该是:

meta(x, tag = "Heading") = csv[[i,10]]  
meta(x, tag = "publisher" ) = csv[[i,16]] 
x

最新更新