【问题标题】:Search for unicode values in character string在字符串中搜索 unicode 值
【发布时间】:2015-08-27 22:33:53
【问题描述】:

我试图在由字符串组成的数据框中识别唯一的 unicode 值。我曾尝试使用 grep 函数,但遇到以下错误

Error: '\U' used without hex digits in character string starting ""\U"

一个示例数据框

                     time sender                                                    message
1     2012-12-04 13:40:00      1                                            Hello handsome!
2     2012-12-04 13:40:08      1                                                 \U0001f618
3     2012-12-04 14:39:24      1                                                 \U0001f603
4     2012-12-04 16:04:25      2                                            <image omitted>
73    2012-12-05 06:02:17      1 Haha not white and blue... White with blue eyes \U0001f61c
40619 2015-05-08 10:00:58      1                                       \U0001f631\U0001f637

grep("\U", dat$messages)

数据

dat <- 
structure(list(time = c("2012-12-04 13:40:00", "2012-12-04 13:40:08", 
"2012-12-04 14:39:24", "2012-12-04 16:04:25", "2012-12-05 06:02:17", 
"2015-05-08 10:00:58"), sender = c(1L, 1L, 1L, 2L, 1L, 1L), message = c("Hello handsome!", 
"\U0001f618", "\U0001f603", "<image omitted>", "Haha not white and blue... White with blue eyes \U0001f61c", 
"\U0001f631\U0001f637")), .Names = c("time", "sender", "message"
), class = "data.frame", row.names = c("1", "2", "3", "4", "73", 
"40619"))

【问题讨论】:

    标签: r regex unicode


    【解决方案1】:

    我假设“unicode 字符”只是指非 ASCII 字符。字符代码可能意味着不同的东西,具体取决于编码。 R 用特殊的\U 序列表示当前编码之外的值。请注意,斜线和字母“U”实际上都不会出现在实际数据中。这就是当相应的字形不可用时它们被转义以在屏幕上打印的方式。

    例如,尽管最后一条消息看起来很长,但实际上只有两个字符

    dat$message[6]
    # [1] "\U0001f631\U0001f637"
    nchar(dat$message[6])
    # [1] 2
    

    您可以很容易地使用正则表达式找到非 ASCII 代码。 ASCII 字符都有代码 0-128(或八进制的 000 到 177)。您可以使用

    找到该范围之外的值
    grep("[^\001-\177]", dat$message)
    # [1] 2 3 5 6
    

    【讨论】:

    • 谢谢,成功了。然后我将如何使用它来提取每行中的单个非 ACSII 字符?
    • 要提取你想要使用gregexpr而不是grep。例如:m&lt;-gregexpr("[^\001-\177]", dat$message); regmatches(dat$message, m)
    【解决方案2】:

    试试:

    library(stringi)
    stri_enc_isascii(dat$message)
    

    这给出了:

    # [1]  TRUE FALSE FALSE  TRUE FALSE FALSE
    

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      相关资源
      最近更新 更多