【问题标题】:Decode utf8 to regular characters in python/R在 python/R 中将 utf8 解码为常规字符
【发布时间】:2019-09-05 10:27:21
【问题描述】:

我有各种字符串,例如xc3\x93\xc5\x81 这些是编码的 UTF-8 字符。我可以访问的唯一文件是那些编码值。如何在 R 或 python 中将其解码为常规字符(不是这个 UTF-8 俚语)?

【问题讨论】:

  • 尝试使用字符串的decode()方法。
  • 在 R 中,尝试stringi::stri_unescape_unicode

标签: python r encoding utf


【解决方案1】:

在 R 中,我们可以在 https://stackoverflow.com/a/24958365/6197649 处使用 @Jeroen 的函数,稍作修改以处理 \xnn 而不是 \unnnn

unescape_unicode <- function(x){
  #single string only
  stopifnot(is.character(x) && length(x) == 1)

  #find matches
  m <- gregexpr("(\\\\)+x[0-9a-z]{2}", x, ignore.case = TRUE)

  if(m[[1]][1] > -1){
    #parse matches
    p <- vapply(regmatches(x, m)[[1]], function(txt){
      gsub("\\", "\\\\", parse(text=paste0('"', txt, '"'))[[1]], fixed = TRUE, useBytes = TRUE)
    }, character(1), USE.NAMES = FALSE)

    #substitute parsed into original
    regmatches(x, m) <- list(p)
  }

  x
}
f <- tempfile()
cat("\\xc3\\x93\\xc5\\x81\n", file = f)
fpeek::peek_head(f)
#> \xc3\x93\xc5\x81

x <- readLines(f)
unlink(f)

unescape_unicode(x)
#> [1] "ÓŁ"

有趣的是,stringi::stri_escape_unicode 给出了不同的结果,似乎将\xc3\x93 误解为两个单独的字符(当它应该只是一个时,"\xc3\x93" == "\u00d3",但我对哪个约定感到困惑确定这一点,我希望有人能更清楚地了解 cmets 中的主题)

stringi::stri_unescape_unicode(x)
#> [1] "Ã\u0093Å\u0081"

reprex package (v0.2.1) 于 2019-04-15 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多