gpt4 book ai didi

r - 在 R 中将字符串转换为十六进制

转载 作者:行者123 更新时间:2023-12-04 15:17:32 25 4
gpt4 key购买 nike

我到处寻找答案,但找不到合适的答案。我需要将字符串转换为 R 中的特定编码,但无法这样做:

string <- "überhaupt"
我需要什么:“überhaupt”
到目前为止我使用过的以下功能:
textutils::HTMLencode(string) gives:  "&uuml;berhaupt"
utf8::utf8_print(string, utf8 = F) gives: "\u00fcberhaupt"
iconv(string, from = "windows-1252", "utf-8") gives: "überhaupt"
似乎我需要十六进制数字字符引用 https://en.wikipedia.org/wiki/%C3%9C但我不知道如何转换。
谢谢你的帮助

最佳答案

所以看起来您想要来自该页面的“数字字符引用”编码。我不确定是否有内置函数,但这是编写这样一个函数的一次尝试

char_ref_encode <- function(x) {
cp <- charToRaw(x)
parts <- rle(cp>127)
with(parts, {
starts <- head(cumsum(c(0, lengths)), -1) + 1
ends <- cumsum(lengths)
paste0(mapply(function(v, start, end) {
if (v) {
paste(sprintf("&#x%02x;", as.numeric(cp[start:end])), collapse="")
} else {
intToUtf8(cp[start:end])
}
}, values, starts, ends), collapse="")
})
}

char_ref_encode("überhaupt")
# [1] "&#xfc;berhaupt"
基本思想是查找所有非 ascii 字符,然后用它们的十六进制值对它们进行编码。

关于r - 在 R 中将字符串转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64033934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com