docs <- Corpus(DirSource(cname))
我有一个目录由cname其中有文本文件(1.txt,2.txt,.... 10.txt,11.txt, ..),我想按照编号顺序创建语料库(如1,2,3,...,10,11 ..),但语料库的词典顺序为1,10,11,... 19,2所以我怎样才能确保语料库按照我要求的顺序读取目录中的文件。读取文本文件的编号顺序为从目录中的语料库R
谢谢,
docs <- Corpus(DirSource(cname))
我有一个目录由cname其中有文本文件(1.txt,2.txt,.... 10.txt,11.txt, ..),我想按照编号顺序创建语料库(如1,2,3,...,10,11 ..),但语料库的词典顺序为1,10,11,... 19,2所以我怎样才能确保语料库按照我要求的顺序读取目录中的文件。读取文本文件的编号顺序为从目录中的语料库R
谢谢,
这里有一些尝试。
# 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
。
对不起,先生,这不符合你的建议。 通过您的代码,当我从1.txt到22.txt文件时,顺序是遵循模式,10.txt,20.txt,1.txt,11.txt,21.txt,12.txt。 –
正则表达式不起作用;我认为现在已经解决了。另外,还包括一个希望模仿你的文件结构的例子。 – jlhoward
将前9个文本文件重命名为01.txt,02.txt等怎么样? – phiver