[英]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(...)
返回类DirSource
的对象,它有一个元素$filelist
。 这是文件名的向量(按您不想要的顺序)。 上面的代码(应)提取物之前的文件数".txt"
,将其转换成整数,以便filesource
基于所述整数值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.