如果编码错误,模式参数将不起作用。使用list.files() 而不使用pattern=...,您至少可以从错误编码的文件名中获取字符串,然后您可以在R 中使用并可能修复这些字符串。
这是一个最小的演示示例(需要convmv 系统命令来设置测试用例)
dir.create( wd <- tempfile() )
setwd(wd)
convmv <- Sys.which("convmv")
if( convmv == "" )
stop("Need the convmv available to continue")
f1 <- "æøå.txt"
cat( "foo\n", file=f1 )
system2( convmv, args=c("-f", "utf8", "-t", "latin1", "--notest", f1) )
f2 <- "ÆØÅ.txt"
cat( "bar\n", file=f2 )
plain.list.files <- list.files()
stopifnot( length( plain.list.files ) == 2 )
with.pattern.list.files <- list.files( pattern="\\.txt" )
stopifnot( length( with.pattern.list.files ) == 1 )
可以修复字符集,但我不确定您此时是否在问这个问题。
编辑:实际使用或修复这些文件名:
现在您可以阅读这些文件,它们可能有多糟糕,如果您知道它们是 latin1,例如,以下内容可能会有所帮助。具有讽刺意味的是,detect_str_enc 并不正确(而且我没有找到好的替代方案),但是如果您知道任何不是 ASCII 或 UTF-8 的文件名都是 latin1,那么这可能是一个适合您的解决方法:
library(uchardet)
hard.coded.encoding <- "latin1"
nice.filenames <- sapply( plain.list.files, function(fname) {
if( !detect_str_enc(fname) %in% c("ASCII","UTF-8") ) {
Encoding(fname) <- hard.coded.encoding
}
return( fname )
})
## Now its presumably safe to look for our pattern:
i.txt <- grepl( "\\.txt$", nice.filenames )
## And we can now work with the files and present them nicely:
file.data <- lapply( plain.list.files[i.txt], function(fname) {
## Do what you want to do with the file here:
readLines( fname )
})
names(file.data) <- nice.filenames[i.txt]