R:用 unicode 代码替换非 ascii 字符[重复]

问题描述 投票:0回答:2

我需要用它们的 unicode 等效项替换特殊字符,例如“č”、“š”、“ž”(原因是由于可移植性,包中不允许使用非 ASCII 字符。我正在尝试编写一个函数来替换它们,但遇到了转义字符的问题。

这是我所知道的(只是为了展示不同数量的反斜杠会发生什么):

replace_characters_with_unicode <- function(input_string) {
  replacements <- list(
    "č" = "\u010d",
    "š" = "\\u0161",
    "ž" = "\\\\u017e"  )

  for (pattern in names(replacements)) {
    input_string <- gsub(pattern, replacements[[pattern]], input_string)
  }
  input_string
}


> replace_characters_with_unicode("č")
[1] "č"
> replace_characters_with_unicode("š")
[1] "u0161"
> replace_characters_with_unicode("ž")
[1] "\\u017e"

此时我也尝试用单个反斜杠替换双反斜杠,但没有成功..

do理解反斜杠是转义字符(在这种情况下以多种方式),我似乎无法找到摆脱这种初始风格情况的方法..

编辑:再次,因为我显然对此不清楚:这是关于获得一个单个反斜杠,而不是“两个反斜杠真正意味着一个”。因此,像thisone这样的答案会产生两个反斜杠,它回答的问题与我的不同。

对于认为这个答案也相关的审稿人来说,不,是另一种方式:那个解释了为什么我需要使用

\uxxxx
转义,但我的问题是如何做到这一点而不需要手动将它们全部输入出来。

r replace unicode character-encoding
2个回答
1
投票

您可以使用 stri_escape_unicode

 包中的 
stringi
 函数:

examples <- c("č", "š", "ž")

library(stringi)

converted <- stri_escape_unicode(examples)

# Output:
[1] "\\u010d" "\\u0161" "\\u017e"

# and then converted back:
stri_unescape_unicode(converted)

# Output:
[1] "č" "š" "ž"

0
投票

您可以使用

{constructive}
包中的函数 construct()

replacements <- c("č", "š", "ž")
constructive::construct(replacements)
#> c("\U{10D}", "\U{161}", "\U{17E}")
© www.soinside.com 2019 - 2024. All rights reserved.