r-在数据表的列值中搜索dict中的字符串



有一个data.table dt,它有一列,每行都有文本语句(dt$text(。然后,有一个包含短语的词典(较小的数据表,包含短语列:dict$word和dict$lookup_n列,包含一个数字,对应于词典中的每个短语(。

我需要遍历dt中的每个句子值,如果字典中的短语是dt sencence(字符串(的一部分,则将短语放在dt$yes列中,并将dict的dict$lookup_n列中的值放在dt列dt$lookup_num中。哪种方法最快?我知道,我可以用:grepl("search_word,"text_to_search",fixed=TRUE(在文本字符串中搜索文本。我试着做以下(示例(brueforece循环:

dt = data.table( text = c('cat, dog books.', 'horse', 'kits fits. mits, bits')) 
dt$yes <- ''
dt$lookup_num <- 0
dt
dict = data.table( word = c('cat, dog ', 'kits'), lookup_n = c(8, 7))
#working!
for(i in 1:nrow(dt)) {
for (j in 1:nrow(dict)){
if (dt[i, 'yes'] == '' & grepl(dict[j,word], dt[i,text], fixed=TRUE)) { 
dt[i,'yes'] <- dict[j,word]
dt[i,'lookup_num'] <- dict[j,lookup_n]}
}
}
dt

此外,还有什么比通过dt和dict循环更快的方法吗?

下面是一个data.table解决方案。我从清理dict开始,因为(I(在每次迭代中清理字典和(ii(一开始就有一个不整洁的字典是没有意义的。

代码

# Clean the dictionary:
dict = dict[, .(word = unlist(strsplit(gsub(' ', '', word), ','))), keyby = lookup_n]
# Apply matching of word from dict
dt[, yes := sapply(text, function(x){
cleanx = gsub('[.]|[,]', '', x)
strings = unlist(strsplit(cleanx, ' '))
num = dict[word %in% strings, word]
})]
# Extract lookup_n from dict
dt[, lookup_n := lapply(yes, function(y) dict[word %in% y, unique(lookup_n)])]

结果

> dt
text     yes lookup_n
1:       cat, dog books. cat,dog        8
2:                 horse                 
3: kits fits. mits, bits    kits        7

数据

dt = data.table( text = c('cat, dog books.', 'horse', 'kits fits. mits, bits')) 
dict = data.table(word = c('cat, dog ', 'kits'), lookup_n = c(8, 7))

最新更新