“match”的优点,它从词典中返回匹配的索引 缺点是它不接受正则表达式
Corpus<- c('animalada', 'fe', 'fernandez', 'ladrillo')
Lexicon<- c('animal', 'animalada', 'fe', 'fernandez', 'ladr', 'ladrillo')
Index <- match(Corpus, Lexicon)
match
返回字典的索引
Index
# [1] 2 3 4 6
Lexicon[Index]
# [1] "animalada" "fe" "fernandez" "ladrillo"
我需要使用包含正则表达式的字典
Lexicon<- c('anima.+$', '.*ez$', '^fe.*$', 'ladr.*$')
“匹配”功能有问题,不适用于正则表达式!
使用
str_which
+ sapply
。请注意,一个正则表达式可以应用于多个值,因此有此列表。
library(stringr)
sapply(Corpus, \(x) str_which(x, Lexicon))
# $animalada
# [1] 1
#
# $fe
# [1] 3
#
# $fernandez
# [1] 2 3
#
# $ladrillo
# [1] 4
跟进@Maël的回答,如果您需要返回Lexicon的实际值,这里有一个有用的习惯用法(假设两个列表之间的关系是一对一的:
library(stringr)
Lexicon[sapply(Corpus, \(x) str_which(x, Lexicon))]