【问题标题】:Position of Approximate Substring Matches in RR中近似子串匹配的位置
【发布时间】:2015-10-28 20:36:20
【问题描述】:

我正在使用 R 进行字符串处理。我有一个带有一列字符串的数据框,比如:

 df <- data.frame(textcol=c("In this substring would like to find the position of this substring",
 "I would also like to find the position of thes substring",
 "No match here","No mention of this substrangy thing"))

 matchPattern <- "this substring"

我正在搜索一个函数(取决于某种距离参数,比如 Jarro-Winkler)将采用我的 matchPattern,将其与数据框文本列的每一行进行比较,并返回匹配的确切位置在匹配的字符串中,即第一个元素为 36(除非我记错了),第二个元素(可能)为 43,第三个元素为 NA,第四个元素为 14(?)。

【问题讨论】:

    标签: r fuzzy-comparison


    【解决方案1】:

    你可以使用aregexec

    ## Get positions (-1 instead of NA)
    positions <- aregexec(matchPattern, df$textcol, max.distance = 0.1)
    unlist(positions)
    # [1] 38 43 -1 15
    
    ## Extract matches
    regmatches(df$textcol, positions)
    # [[1]]
    # [1] "this substring"
    # 
    # [[2]]
    # [1] "thes substring"
    # 
    # [[3]]
    # character(0)
    # 
    # [[4]]
    # [1] "this substrang"
    

    编辑

    ## A possibilty for replacing matches, or maybe `regmatches<-`
    res <- regmatches(df$textcol, positions)
    res[lengths(res)==0] <- "XXXX"  # deal with 0 length matches somehow
    df$out <- Vectorize(gsub)(unlist(res), "Censored", df$textcol)
    df$out
    # [1] "I would like to find the position of Censored"     
    # [2] "I would also like to find the position of Censored"
    # [3] "No match here"                                     
    # [4] "No mention of Censoredy thing"                     
    

    【讨论】:

    • 感谢 nongkrong!你能非常简要介绍一下它是如何工作的吗?我之前尝试过使用 aregexec 并且很生气。
    • @SerbanTanasa 你的意思是匹配算法吗?因为我不知道,但从?agrep 看来,它使用的是 Levenshtein 距离。
    • 不,不,只是假设我想在原始 data.frame 中用“Censored”替换每个实例。例如,如果模式在一种情况下重复多次。
    • @SerbanTanasa 有一个替换功能,regmatches&lt;-,您可能会使用它。如果您查看?regmatches,则在底部有一个如何构造替换的示例。
    • @SerbanTanasa 你也可以考虑使用gsub,我加了一个例子
    猜你喜欢
    • 2013-04-15
    • 2015-02-12
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多