我想看一下我的数据集中的单词是否出现在某个文本中。使用grepl
时,您只能获得完全匹配。使用agrepl
,可以进行部分匹配。但是,我没有得到预期的结果。
示例数据:
dt <- structure(list(id = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L),
words = c("weg", "verte", "spiegelend", "spiegeld", "einde", "spiegel", "spiegelende", "weg", "spiegelend", "asfalt", "fata", "morgana")),
.Names = c("id", "words"), row.names = c(NA, -12L), class = c("data.table", "data.frame"))
使用:
dt <- dt[, .(id, words,
match1=mapply(grepl, words,
"hoe komt het dat de weg in de verte soms spiegelend lijkt"),
match2=mapply(agrepl, words,
"hoe komt het dat de weg in de verte soms spiegelend lijkt",
MoreArgs=list(max.distance=1L)))]
我明白了:
> dt
id words match1 match2
1: 0 weg TRUE TRUE
2: 0 verte TRUE TRUE
3: 0 spiegelend TRUE TRUE
4: 0 spiegeld FALSE TRUE
5: 0 einde FALSE FALSE
6: 0 spiegel TRUE TRUE
7: 0 spiegelende FALSE TRUE
8: 1 weg TRUE TRUE
9: 1 spiegelend TRUE TRUE
10: 1 asfalt FALSE FALSE
11: 1 fata FALSE FALSE
12: 1 morgana FALSE FALSE
正如您所看到的,grepl
和agrepl
的结果在第4行和第7行上有所不同。但是,我只希望在最多只有一个字母差异时进行匹配。因此,match2
第4行中的匹配应为FALSE
。更改max.distance
或costs
等参数也不会产生预期的结果。此外,第6行的两个匹配也应该是FALSE
。
例如:对于文本中的单词“ spiegelend ”,单词“ spiegelende ”应该给出匹配(只有一个字母的差异),但单词“ spiegeld “(两个字母差异)和单词” spiegel “(三个字母差异)应不给出匹配。
允许条件(但不允许同时):
关于如何解决这个问题的任何想法?
答案 0 :(得分:2)
我考虑在这种情况下使用T
条件A
。但我不确定它是否会产生预期的输出。这有帮助吗?
adist()
数据强>
< 2
答案 1 :(得分:2)
两种解决方法,与nongkrong和RHertel的方法相匹配:
dt <- cbind(dt[,c("id", "words")],
match1=mapply(grepl, dt$words,
"hoe komt het dat de weg in de verte soms spiegelend lijkt"),
match2=mapply(agrepl, dt$words,
"hoe komt het dat de weg in de verte soms spiegelend lijkt",
MoreArgs=list(max.distance=1L)),
match3=mapply(agrepl, paste0("\\b",dt$words,"\\b"),
"hoe komt het dat de weg in de verte soms spiegelend lijkt",
MoreArgs=list(max.distance=1L, fixed=F)),
match4=apply(adist( dt$words, unlist(strsplit("hoe komt het dat de weg in de verte soms spiegelend lijkt", split=" "))),
1, function (x) any(x<=1))
)
match3使用单词boundary \\ b,而match4使用&lt; = 1的编辑距离(adist)到向量中的单个单词