考虑以下逗号分隔文件。为简单起见,让它包含一行:
'I am quoted','so, can use comma inside - it is not separator here','but can\'t use escaped quote :=('
如果您尝试使用命令读取它
table <- read.csv(filename, header=FALSE)
该行将被分成 4 部分,因为该行包含 3 个逗号。事实上,我只想阅读 3 个部分,其中一个包含逗号本身。有引用标志来寻求帮助。我试过:
table <- read.csv(filename, header=FALSE, quote="'")
但这会出现错误
"incomplete final line found by readTableHeader on table"
.这是由于奇数(七)个引号引起的。read.table()
以及 scan()
有参数 allowEscapes
,但将其设置为 TRUE
没有帮助。没关系,原因来自 help(scan)
你可以阅读:The escapes which are interpreted are the control characters ‘\a, \b, \f, \n, \r, \t, \v’, ... ... Any other escaped character is treated as itself, including backslash
请建议您如何阅读此类引用的 csv 文件,其中包含转义
\'
引号。
最佳答案
一种可能性是使用 readLines()
按原样读取所有内容,然后将引号字符替换为其他内容,例如:
tt <- readLines("F:/temp/test.txt")
tt <- gsub("([^\\]|^)'","\\1\"",tt) # replace ' by "
tt <- gsub("\\\\","\\",tt) # get rid of the double escape due to readLines
这允许您使用
textConnection
读取向量 ttzz <- textConnection(tt)
read.csv(zz,header=F,quote="\"") # give text input
close(zz)
不是最漂亮的解决方案,但它有效(前提是您在文件中的某处没有 "字符当然...)
关于r - 如何阅读包含转义引号的引用文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6032296/