Положение приближенных совпадений подстрок в R
Я использую 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 (?) для четвертого.
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"