【问题标题】:How to calculate longest common substring anywhere in two strings如何计算两个字符串中任意位置的最长公共子字符串
【发布时间】:2020-10-06 17:49:31
【问题描述】:

我正在尝试计算 R 中字符串和字符串向量之间没有间隙的最长精确公共子字符串。如何修改 stringdist 以返回两个比较字符串中任何位置的任何公共字符串并返回距离?

重现数据:

string1 <- "whereiam"
vec1 <- c("firstiam","twoiswhereiaminthisvec","thisisthree","fouriamhere","fivewherehere")

尝试了 stringdist 函数(不适用于我的目的):

library(stringdist)
stringdistvec <- stringdist(string1,vec1,method="lcs")
[1]  8 14 13 11 11  #not calculating the lcs type I want

想要的结果,而不是匹配的解释:

#desired to work to get this result:

desired_stringdistvec <- c(3,8,1,3,5)
[1]  3 8 1 3 5
#match 1: iam (3 common substr)
#match 2: whereiam (8 common substr)
#match 3: i (one letter only)
#match 5: iam (3 common substr)
#match 6: where (5 common substr)

【问题讨论】:

    标签: r string substring lcs stringdist


    【解决方案1】:

    一种方法可能是查看adist() 生成的转换序列并计算最长连续匹配中的字符:

    trafos <- attr(adist(string1, vec1, counts = TRUE), "trafos")
    sapply(gregexpr("M+", trafos), function(x) max(0, attr(x, "match.length")))
    
    [1] 3 8 1 3 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多