如何显示unicode字符串,例如:
x <- "•"
Run Code Online (Sandbox Code Playgroud)
使用其转义的等价物?
y <- "\u2022"
identical(x, y)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)
(我希望能够这样做,因为CRAN包必须只包含ASCII,但有时你想在错误信息中使用unicode或类似的)
Xin*_*Yin 14
在深入研究一些文档之后iconv
,我认为你只能使用这个base
包完成这个.但是你需要特别注意字符串的编码.
在具有UTF-8编码的系统上:
> stri_escape_unicode("????")
[1] "\\u4f60\\u597d\\u4e16\\u754c"
# use big endian
> iconv(x, "UTF-8", "UTF-16BE", toRaw=T)
[[1]]
[1] 4f 60 59 7d 4e 16 75 4c
> x <- "•"
> iconv(x, "UTF-8", "UTF-16BE", toRaw=T)
[[1]]
[1] 20 22
Run Code Online (Sandbox Code Playgroud)
但是,如果您使用的是带latin1
编码的系统,则可能会出现问题.
> x <- "•"
> y <- "\u2022"
> identical(x, y)
[1] FALSE
> stri_escape_unicode(x)
[1] "\\u0095" # <- oops!
# culprit
> Encoding(x)
[1] "latin1"
# and it causes problem for iconv
> iconv(x, Encoding(x), "Unicode")
Error in iconv(x, Encoding(x), "Unicode") :
unsupported conversion from 'latin1' to 'Unicode' in codepage 1252
> iconv(x, Encoding(x), "UTF-16BE")
Error in iconv(x, Encoding(x), "UTF-16BE") :
embedded nul in string: '\0•'
Run Code Online (Sandbox Code Playgroud)
在转换为Unicode之前将字符串转换为UTF-8更安全:
> iconv(enc2utf8(enc2native(x)), "UTF-8", "UTF-16BE", toRaw=T)
[[1]]
[1] 20 22
Run Code Online (Sandbox Code Playgroud)
编辑:这可能会导致某些特定系统上已经采用UTF-8编码的字符串出现问题.也许在转换之前检查编码更安全.
> Encoding("•")
[1] "latin1"
> enc2native("•")
[1] "•"
> enc2native("\u2022")
[1] "•"
# on a Windows with default latin1 encoding
> Encoding("??")
[1] "UTF-8"
> enc2native("??")
[1] "<U+6D4B><U+8BD5>" # <- BAD!
Run Code Online (Sandbox Code Playgroud)
对于某些角色或语言,UTF-16
可能还不够.所以,很可能你应该使用UTF-32
,因为
UTF-32形式的字符是其代码点的直接表示.
基于上述试验和错误,下面可能是我们可以编写的一个更安全的逃避函数:
unicode_escape <- function(x, endian="big") {
if (Encoding(x) != 'UTF-8') {
x <- enc2utf8(enc2native(x))
}
to.enc <- ifelse(endian == 'big', 'UTF-32BE', 'UTF-32LE')
bytes <- strtoi(unlist(iconv(x, "UTF-8", "UTF-32BE", toRaw=T)), base=16)
# there may be some better way to do thibs.
runes <- matrix(bytes, nrow=4)
escaped <- apply(runes, 2, function(rb) {
nonzero.bytes <- rb[rb > 0]
ifelse(length(nonzero.bytes) > 1,
# convert back to hex
paste("\\u", paste(as.hexmode(nonzero.bytes), collapse=""), sep=""),
rawToChar(as.raw(nonzero.bytes))
)
})
paste(escaped, collapse="")
}
Run Code Online (Sandbox Code Playgroud)
> unicode_escape("•••ERROR!!!•••")
[1] "\\u2022\\u2022\\u2022ERROR!!!\\u2022\\u2022\\u2022"
> unicode_escape("Hello word! ?????")
[1] "Hello word! \\u4f60\\u597d\\u4e16\\u754c!"
> "\u4f60\u597d\u4e16\u754c"
[1] "????"
Run Code Online (Sandbox Code Playgroud)
该软件包stringi
有一个执行此操作的方法
stri_escape_unicode(y)
# [1] "\\u2022"
Run Code Online (Sandbox Code Playgroud)