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

时间:2015-09-27 16:45:56

标签: r corpus

docs <- Corpus(DirSource(cname))

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

谢谢,

1 个答案:

答案 0 :(得分: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(...)会返回类DirSource的对象,该对象具有元素$filelist。这是文件名的向量(按照您不想要的顺序)。上面的代码(应该)提取".txt"之前的文件编号,将其转换为整数,并根据整数值排序filesource