2

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

例子:

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
)
4

1 回答 1

2

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

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

这可以包装在一个函数中,该函数同时使用 和 的aregexec参数regmatches。请注意,在后一种情况下,函数参数位于点参数之后,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."
于 2019-11-18T13:00:20.640 回答