r - 如何阅读包含转义引号的引用文本

标签 r escaping quotes multiline read.csv

考虑以下逗号分隔文件。为简单起见,让它包含一行:

'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 读取向量 tt
zz <- textConnection(tt)
read.csv(zz,header=F,quote="\"") # give text input
close(zz)

不是最漂亮的解决方案,但它有效(前提是您在文件中的某处没有 "字符当然...)

关于r - 如何阅读包含转义引号的引用文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6032296/

相关文章:

ios - NSURL 用冒号打破端口字符串

python - Pyschool 测验——字符串连接

c++ - 单引号在 C++ 中用于多个字符时有什么作用?

mysql - MySQL 中何时使用单引号、双引号和反引号

r - 如何写一个固定宽度的文件?

r - Dplyr 在指定位置改变新列

linux - perl 中的 '\b' 字符是如何工作的?

php - 将单引号字符串转换为双引号

r - 在多列上使用 tidyr::complete

r - 如何在dplyr中调用多个变量到group_by