【问题标题】:Extract substring match from agrep从 agrep 中提取子字符串匹配
【发布时间】:2023-03-17 07:02:01
【问题描述】:

我的目标是确定给定的text 中是否有target 字符串,但我想允许拼写错误/小的派生并提取“导致”匹配的子字符串(以将其用于进一步的文本分析)。

示例:

target <- "target string"
text <- "the target strlng: Butter. this text i dont want to extract."

所需的输出:

我想将target strlng 作为输出,因为它非常接近目标(levenshtein 距离为 1)。接下来我想使用target strlng 提取单词Butter(这部分我已经介绍过,我只是添加它以获得详细的规范)。

我尝试了什么:

使用 adist 不起作用,因为它比较两个字符串,而不是子字符串。

接下来我看了一下agrep,它看起来很接近。我可以找到我的目标的输出,但不是“导致”匹配的substring

我尝试使用value = TRUE,但它似乎适用于阵列级别。我认为我不可能切换到数组类型,因为我不能用空格分割(我的目标字符串可能有空格,...)。

agrep(
  pattern = target, 
  x = text,
  value = TRUE
)

【问题讨论】:

    标签: r levenshtein-distance agrep


    【解决方案1】:

    使用aregexec,类似于使用regexpr/regmatches(或gregexpr)进行精确匹配提取。

    m <- aregexec('string', 'text strlng wrong')
    regmatches('text strlng wrong', m)
    #[[1]]
    #[1] "strlng"
    

    这可以包装在一个使用aregexecregmatches 的参数的函数中。请注意,在后一种情况下,函数参数 invert 位于 点参数 ... 之后,因此它必须是命名参数。

    aregextract <- function(pattern, text, ..., invert = FALSE){
      m <- aregexec(pattern, text, ...)
      regmatches(text, m, invert = invert)
    }
    
    aregextract(target, text)
    #[[1]]
    #[1] "target strlng"
    
    aregextract(target, text, invert = TRUE)
    #[[1]]
    #[1] "the "                                       
    #[2] ": Butter. this text i dont want to extract."
    

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2017-12-14
      • 2015-10-19
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多