【发布时间】:2016-07-06 15:33:57
【问题描述】:
我有一个通过网络抓取创建的非常大的数据集(70k 行,2600 列,CSV 格式)。不幸的是,在某些时候进行预处理、处理等一些有问题的字符已经以一种奇怪的方式编码,我在处理它们时遇到了问题。
我有如下字符串:
x = "but it doesn<U+0092>t matter"
Looking up the code,我们可以看到应该是’这个字符,实际上应该是'(数据是用户生成的,所以可能包含各种奇数字符)。虽然从那个角色来看,似乎其他人也有问题(1,2,3)。它被标记为控制字符,不知道那是什么,但也许这就是它如此难以处理的原因。
关于 R 中的 Unicode 的其他大多数问题都与 \u0092 等格式的 Unicode 有关。
只需使用Encoding()
我们试试吧:
#> x = "but it doesn<U+0092>t matter"
#> Encoding(x)
#[1] "unknown"
#> Encoding(x) = "UTF-8"
#> Encoding(x)
#[1] "unknown"
#> x
#[1] "but it doesn<U+0092>t matter"
所以这似乎没有任何作用。
使用上述问题中的 hack 函数
之前有几个问题涉及这种 Unicode 格式并尝试转换它们:
- Display unicode in R
- gsub in R with unicode replacement give different results under Windows compared with Unix?
奇怪的是,他们给出的例子有效,但我的没有。
#> test.string <- "This is a <U+03B1> <U+03B2> <U+03B2> <U+03B3> test <U+03B4> string."
#> Encoding(test.string)
#[1] "unknown"
#> to_true_unicode(test.string)
#[1] "This is a α β β γ test δ string."
但是:
#> x2 = to_true_unicode(x)
#> x2
#[1] "but it doesn\u0092t matter"
#> cat(x2)
#but it doesnt matter
#> Encoding(x2)
#[1] "UTF-8"
因此,它设法从 U+....> 格式转换为 \u 格式,并使用 cat() 打印没有该符号的字符(或 SO 上的错误符号)。
只需手动搜索和替换它们
我只有有限数量的这些问题,所以我也许可以使用搜索替换来解决它。然而:
#> #base-r
#> gsub(x = x, pattern = "<U+0092>", replacement = "'")
#[1] "but it doesn<U+0092>t matter"
#> #stringr/stringi
#> library(stringr)
#> str_replace(x, pattern = "<U+0092>", "'")
#[1] "but it doesn<U+0092>t matter"
所以替换似乎不起作用,但它确实适用于 \u 版本:
#> #base-r
#> gsub(x = x2, pattern = "\u0092", replacement = "'")
#[1] "but it doesn't matter"
#> #stringr/stringi
#> library(stringr)
#> str_replace(x2, pattern = "\u0092", "'")
#[1] "but it doesn't matter"
因此,这提出了一种工作方法:1)将<U+>格式转换为\u格式,然后使用搜索替换。
用stringi::stri_unescape_unicode()取消转义
似乎不适用于任一版本:
#> stringi::stri_unescape_unicode(x)
#[1] "but it doesn<U+0092>t matter"
#> stringi::stri_unescape_unicode(x2)
#[1] "but it doesn\u0092t matter"
是否有一些普遍适用的方法来处理此类问题?
我的设置
我的 sessionInfo 是:
> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=Danish_Denmark.1252 LC_CTYPE=Danish_Denmark.1252 LC_MONETARY=Danish_Denmark.1252
[4] LC_NUMERIC=C LC_TIME=Danish_Denmark.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] stringr_1.0.0
loaded via a namespace (and not attached):
[1] magrittr_1.5 tools_3.2.3 stringi_1.0-1
在 64 位 Windows 8.1 上通过 RStudio(0.99.893,预览版)运行 R。键盘和时间单位是丹麦语,但其他一切都是英语。
【问题讨论】:
-
¿你能用 R 解决问题吗?我遇到了完全相同的问题。