如何修复 tm 包以奇怪的顺序加载大量文件?

How to fix the tm package loading large amounts of documents in strange order?

我在 R 中使用 tm,并处理 10k 个文档。我想按索引检查一些,但它们与文件不匹配。为什么tm以奇怪的顺序加载大量文档,怎么会是fixed/subverted?这是一个例子:

library(tm)

docs <- c()
for (i in 1:10000) {
  docs <- c(docs, paste('test', i))
}

cor <- VCorpus(VectorSource(docs))

filepath = '/home/nate/Dropbox/MSDS/MSDS682_ncg_F8W2_17/test_cor'
writeCorpus(cor, path = filepath)

cor2 <- VCorpus(DirSource(filepath))

as.character(cor2[[1]])
as.character(cor2[[2]])
as.character(cor2[[3]])
as.character(cor2[[4]])

打印出来:

test 10000
test 1000
test 1001
test 1002

这个结果是由于 writeCorpus 创建的文件名造成的。在您的 path 中,您会找到名为 1.txt, 10.txt, 100.txt, 1000.txt, 1001.txt ... n.txt

的文件

当您使用 DirSource 读回它们时,它们将使用该文本排序而不是您预期的数字。

要保持​​您的排序顺序符合预期,您可以将 filenames 参数添加到 writeCorpus,例如:

writeCorpus(
  cor,
  path = filepath,
  filenames = paste0(sprintf("%05d", 1:length(cor)), ".txt")
)

这将使您的文件输出,00001.txt, 00002.txt, 00003.txt ... n.txt,并且您从磁盘返回的导入将以正确的顺序读取。