我有一个非常大的数据集(70k行,2600列,CSV格式),我通过网络爬虫创建了它。不幸的是,在进行预处理、处理等过程中,某些问题字符以奇怪的方式编码,导致我无法处理它们。
我有以下类似的字符串:
x = "but it doesn<U+0092>t matter"
查找代码,我们可以看到它应该是字符’
,实际上应该是'
(数据由用户生成,可能包含各种奇怪的字符)。虽然从这个字符来看,似乎其他人也有问题(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格式并尝试进行转换:
奇怪的是,他们给出的示例可以工作,但我的却不能。
#> 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
在 Windows 8.1 64 位操作系统上,使用 RStudio(0.99.893 预览版)运行 R。键盘和时间单位为丹麦语,但其他所有内容均为英文。