【问题标题】:Converting from NCR to Unicode in R在 R 中从 NCR 转换为 Unicode
【发布时间】:2020-02-02 13:48:28
【问题描述】:

我有一些利用十进制 NCR 对特殊字符进行编码的 html 文件(我将它们作为纯文本处理)。有没有办法使用 R 方便地将它们转换为 Unicode?
NCR 代码并不总是与 unicode 一对一匹配,而且会变得相当混乱,因为 ѣ 不等于 \u1123,而是等于 \u0463:

> stri_unescape_unicode("\u1123")
[1] "ᄣ"

> stri_unescape_unicode("\u0463")
[1] "ѣ"

【问题讨论】:

标签: r unicode stringi ncr


【解决方案1】:

1123 是十六进制 0463 的十进制等效值,Unicode 使用十六进制。所以为了得到转换,你需要去掉非数字字符,将数字转换为十六进制字符,在它们前面贴一个“\u”,然后使用stri_unescape_unicode

这个函数会做所有这些:

ncr2uni <- function(x)
{
  # Strip out non-digits and and convert remaining numbers to hex
  x <- as.hexmode(as.numeric(gsub("\\D", "", x)))

  # Left pad with zeros to length 4 so escape sequence is recognised as Unicode 
  x <- stringi::stri_pad_left(x, 4, "0")

  # convert to Unicode
  stringi::stri_unescape_unicode(paste0("\\u", x))
}

现在你可以做

ncr2uni(c("&#1123;", "&#1124;", "&#1125;"))
# [1] "ѣ" "Ѥ" "ѥ"

【讨论】:

  • 非常感谢!我根本没有意识到 unicode 是十六进制的。现在我感到既傻又开悟。
猜你喜欢
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
相关资源
最近更新 更多