代码之家  ›  专栏  ›  技术社区  ›  Chris Ruehlemann

提取不允许的字符

  •  0
  • Chris Ruehlemann  · 技术社区  · 4 年前

    我有错误编码的转录,也就是说,出现的字符 不应该 发生

    在这个玩具数据中 允许 字符是此类:

    "[)(/][A-Za-z0-9↑↓£¥°!.,:¿?~<>≈=_-]"
    
    df <- data.frame(
      Utterance = c("~°maybe you (.) >should ¥just¥<",
                    "SOME text |<-- pipe¿ and€",            # <--: | and €
                    "blah%",                                # <--: %
                    "text ^more text",                      # <--: ^
                    "£norm(hh)a::l£mal, (1.22)"))
    

    我需要做的是:

    • 发现 Utterance 包含任何错误编码的
    • 提取错误的字符

    就检测而言,我做得还可以,但提取失败得很惨:

    library(stringr)
    library(dplyr)
    df %>%
      filter(!str_detect(Utterance, "[)(/][A-Za-z0-9↑↓£¥°!.,:¿?~<>≈=_-]")) %>%
      mutate(WrongChar = str_extract_all(Utterance, "[^)(/][A-Za-z0-9↑↓£¥°!.,:¿?~<>≈=_-]"))
                      Utterance                                  WrongChar
    1 SOME text |<-- pipe¿ and€ SO, ME,  t, ex, |<, --,  p, ip, e¿,  a, nd
    2                     blah%                                     bl, ah
    3           text ^more text                     te, xt, ^m, or,  t, ex
    

    如何改进提取以获得此 预期结果 :

                      Utterance WrongChar
    1 SOME text |<-- pipe¿ and€      |, €
    2                     blah%         %
    3           text ^more text         ^
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Wiktor Stribiżew    4 年前

    你需要

    • 确保 [ ] 在字符类中转义
    • 将空白模式添加到两个regexp检查中,因为它的缺失会扰乱结果。

    所以你需要使用

    df %>%
       filter(str_detect(Utterance, "[^\\s)(/\\]\\[A-Za-z0-9↑↓£¥°!.,:¿?~<>≈=_-]")) %>%
       mutate(WrongChar = str_extract_all(Utterance, "[^\\s)(/\\]\\[A-Za-z0-9↑↓£¥°!.,:¿?~<>≈=_-]"))
    

    输出

                      Utterance WrongChar
    1 SOME text |<-- pipe¿ and€      |, €
    2                     blah%         %
    3           text ^more text         ^
    

    注意,我在中使用了正逻辑 filter(str_detect(Utterance, "[^\\s)(/\\]\\[A-Za-z0-9↑↓£¥°!.,:¿?~<>≈=_-]")) ,所以我们得到的所有项至少包含一个字符,而不是允许的字符。