代码之家  ›  专栏  ›  技术社区  ›  Christopher Costello

转换unicode CodePoint格式

  •  0
  • Christopher Costello  · 技术社区  · 6 年前

    假设我有一个字符串,其中包含表示表情符号的字节:

    string <- "This is a test. U+1F600"
    

    如何将其转换为

    string <- "This is a test. \U0001F600"
    

    这样我就可以将其渲染为

    utf8_print("This is a test \U0001F600")
    [1] "This is a test 😀​"
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Patrick Perry    6 年前

    这是一种黑客行为,但它适用于您的情况:

    string <- c("This is a test. U+1F600", "Another test")
    
    # change U+XXXXYYYY to \UXXXXYYYY, quote and encode special characters
    expr <- gsub("U[+]([0-9A-Fa-f]{1,8})", "\\\\U\\1",
                 encodeString(string, quote = '"'))
    
    # evaluate the string as an R expression
    vapply(parse(text = expr, keep.source = FALSE), eval, "")
    #> [1] "This is a test. \U0001f600" "Another test"