删除非 ASCII 值然后降低文本会出错

Removed non-ASCII values and then lowering text is giving error

我清理了一个大数据集,发现其中一个字段的值类似于

"My son is turning into a monster \xf0\u009f\u0098\u0092"

我无法创建这个简单的数据,因为它给出了下面提到的错误

a <- c('My son is turning into a monster \xf0\u009f\u0098\u0092')

Error: mixing Unicode and octal/hex escapes in a string is not allowed

现在假设我的变量中有这个值,并且想删除所有非 ascii 字符,例如

library(stringi)
b <- stri_trans_general(a, "latin-ascii")

现在想以较低格式转换文本

tolower(b)

我遇到下面提到的错误

Error in tolower(b) : invalid input 'My son is turning into a monster 😒' in 'utf8towcs'

有人可以帮我理解这个问题吗

要删除所有非 ASCII 字符,您可以使用正则表达式。 [\x00-\x7F] 是所有非 ASCII 字符的集合,所以我们可以用空替换所有出现的字符。但是,R 不喜欢 \x00 因为它是空字符,所以我不得不将系列修改为 [\x01-\x7F]

a <- c('My son is turning into a monster \u009f\u0098\u0092')
#> [1] "My son is turning into a monster \u009f\u0098\u0092"
tolower(gsub('[^\x01-\x7F]+','',a))
#> [1] "my son is turning into a monster "

或者,使用八进制代码

a <- c('My son is turning into a monster \xf0')
#> [1] "My son is turning into a monster ð"
tolower(gsub('[^\x01-\x7F]+','',a))
#> [1] "my son is turning into a monster "

您可以使用 iconv 删除非 ASCII 字符:

a <- c('My son is turning into a monster \xf0\x9f\x98\x92')
a
[1] "My son is turning into a monster 😒"
iconv(a,to="ASCII",sub="")
[1] "My son is turning into a monster "