【问题标题】:How to get the raw numeric HTML representation of special characters?如何获取特殊字符的原始数字 HTML 表示?
【发布时间】:2019-08-17 18:03:45
【问题描述】:

当我在 R 中输入 "\xfc" 时,它会导致 [1] "ü"。我不希望这样,我希望这导致[1] "\xfc"。我也不太明白为什么Encoding("\xfc")"latin1",尽管我将 Code->Saving 中的设置更改为 UTF-8。我想编写一个函数,用"\xfc" 替换一些特殊字符,如"ü",但我无法实现:

> stringr::str_replace_all("Müller", "ü", "\xfc")
[1] "Müller"
> stringr::str_replace_all("Müller", "ü", "\\xfc")
[1] "Mxfcller"
> stringr::str_replace_all("Müller", "ü", "\\\xfc")
[1] "Müller"
> stringr::str_replace_all("Müller", "ü", "\\\\xfc")
[1] "M\\xfcller"

我真正想要的是[1] "M\xfcller"

(如何)我可以做到这一点?

【问题讨论】:

  • 查看?Quotes,R 似乎将"\xnn" 解释为具有十六进制代码nn 的字符。我不知道这种行为是否有解决方法

标签: r regex encoding special-characters


【解决方案1】:

最后一行给出了你想要的结果。打印字符串时,反斜杠被转义。为了看到这一点,让我们将字符串保存到文件中,然后查看文件的内容。


s <- stringr::str_replace_all("Müller", "ü", "\\\\xfc")

writeLines(s, "test.txt")

cat(readLines("test.txt"))
#> M\xfcller

reprex package (v0.2.1) 于 2019 年 3 月 27 日创建

另请参阅此 GitHub 问题:https://github.com/STAT545-UBC/Discussion/issues/394

【讨论】:

  • x &lt;- readLines("test.txt")。现在x 仍然是"M\\xfcller"。我想将x 传递给另一个函数,而x 必须是"M\xfcller"
  • R 对字符串的处理方式略有不同。如果你尝试x = "M\xfcller",你会得到“Müller”。
  • 另外,您可以在文件中看到该字符串为M\xfcller,但R 显示它为M\\xfcller
  • s &lt;- "a\b"print(s) 导致"a\b" 而不是"a\\b" 所以一定有区别吗?还是我错了?
  • R 不会将“\b”解释为特殊字符。尝试“a\x”,你会得到一个关于“十六进制数字”的错误,这就是“\xfc”。
猜你喜欢
  • 2021-04-26
  • 2016-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 2012-11-26
  • 2022-11-25
相关资源
最近更新 更多