从 R 中的目录中按语料库的编号顺序读取文本文件

Reading text file in numbering order for corpus from directory in R

docs <- Corpus(DirSource(cname))

我有一个 cname 目录,其中包含文本文件 (1.txt,2.txt,....10.txt,11.txt,..)我想按编号顺序创建语料库(如 1,2,3,...,10,11..)但语料库按字典顺序读取为 1,10,11,...19,2 所以如何确保语料库按我要求的顺序读取目录中的文件。

谢谢,

这里有一些可以尝试的东西。

# simulate your file structure - you have this already
txt <- c("This is some text.", "This is some more text.","This is additional text.","Yet more additional text.")
num <- c(1,2,10,20)
td  <- tempdir()     # temporary directory
# creates 4 files in temp dir: 1.txt, 2.txt, 10.txt, and 20.txt
mapply(function(x,y) writeLines(x,paste0(td,"/",y,".txt")),txt,num)

# you start here...
library(tm)
src <- DirSource(directory=td, pattern=".txt")
names(Corpus(src))
# [1] "1.txt"  "10.txt" "2.txt"  "20.txt"
src$filelist <- src$filelist[order(as.integer(gsub("^.*/([0-9]+)\.txt$","\1",src$filelist)))]
names(Corpus(src))
# [1] "1.txt"  "2.txt"  "10.txt" "20.txt"

# clean up: just for this example
unlink(paste(td,"*.*",sep="/"))   # remove sample files...

所以 DirSource(...) returns class DirSource 的一个对象,它有一个元素 $filelist。这是一个文件名向量(按照你不想要的顺序)。上面的代码(应该)提取 ".txt" 之前的文件编号,将其转换为整数,并根据整数值对 filesource 进行排序。