【问题标题】:Read a string with single and doubles quotes读取带有单引号和双引号的字符串
【发布时间】:2015-10-29 17:21:25
【问题描述】:

只是夏天对 R 中的字符串感到好奇。假设我有一个 xy 字符串。正如我们所知,我们必须在双引号中引用单引号,反之亦然。

x <- "a string with 'single' quotes"
y <- 'another one with "double" quotes'

paste0(x, y)
[1] "a string with 'single' quotesanother one with \"double\" quotes"
cat(x, y)
a string with 'single' quotes another one with "double" quotes

如果我们也有一个带有单引号和双引号的字符串怎么办?我试过这个: 反引号不起作用(R 触发错误):

z <- `a string with 'single' quotes and with "double" quotes`

使用\" 代替",然后使用cat: 这很好用,但问题是用户必须在每个双引号中添加一个反斜杠。

z1 <- "a string with 'single' quotes and with \"double\" quotes"

如果我们有一个巨大的 文本 文件(例如 .txt),其中包含两种类型的引号,并且我们想在 R 中读取?

此时对我来说一个(愚蠢的)解决方案似乎是:在 R 之外工作,进行一些操作(例如用 \" 替换所有 "),然后在 R 中读取。 这是一个解决方案还是在 R 中存在更好的方法?

这里只是一个小.txt 文件,例如:Link,不管谁有兴趣,该文件只是一个.txt,其中一行文字:

带有“单”引号和“双”引号的字符串

【问题讨论】:

  • readLines 与蒂姆的回答类似。或者如果你感觉特别困难,你可以使用 perl 和环视
  • 也许最好的答案是在导入 R 之前清理数据并删除引号。
  • 抱歉,延迟添加文本文件,我在使用 Dropbox 时遇到了问题。现在该文件应该可用了。
  • 实际上,链接到 Dropbox 并不是很好,因为不是每个人都会安装它。
  • 请将小版本的测试文件放在问题本身而不是外部链接中。

标签: r string character


【解决方案1】:

您可以在阅读文本时根据需要指定任何备用引号字符,例如

> p<-scan(what="character",quote="`")
1: `It is 'ambiguous' if "this is a new 'string' or "nested" in the 'first'", isn't it?`
2: 
Read 1 item
> p
[1] "It is 'ambiguous' if \"this is a new 'string' or \"nested\" in the 'first'\", isn't it?"

或者,只是阅读原始文本,例如使用@rawr 建议的readline

> readline()
 "It is 'ambiguous' if "this is a new 'string' or "nested" in the 'first'", isn't it?"
[1] "\"It is 'ambiguous' if \"this is a new 'string' or \"nested\" in the 'first'\", isn't it?\""

【讨论】:

    猜你喜欢
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多