将utf8解码为python / R中的常规字符

问题描述 投票:-1回答:1

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

python r encoding utf
1个回答
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",但我对哪个约定决定了我感到困惑,我很欣赏那些对这个主题有更清晰的人的意见在评论中)

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

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

© www.soinside.com 2019 - 2024. All rights reserved.