【问题标题】:Search strings from dict within a data table column values从数据表列值中的 dict 搜索字符串
【发布时间】:2020-02-26 23:19:36
【问题描述】:

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

我需要检查 dt 中的每个句子值,如果字典中的短语是 dt 句子(字符串)的一部分,则将短语放入 dt$yes 列中,并将 dict$lookup_n 列中的值放入 dict一个 dt 列 dt$lookup_num。 最快的方法是什么? 我知道,我可以使用以下命令搜索文本字符串中的文本:grepl("Search_word, "Text_to_search", fixed=TRUE)。 我尝试执行以下(示例)暴力循环:

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 更快的方法?

【问题讨论】:

  • 你能分享dput(dict)dput(dt)的输出吗?如果很大,请申请head(data, 20)

标签: r string dictionary search data.table


【解决方案1】:

以下是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))

【讨论】:

  • 非常感谢!但是如果我不能用分隔符分割句子呢? dt = data.table( text = c('cat, dog books.', 'horse', 'kits fit. mits, bits') ) dict = data.table( word = c('cat', 'kits')长度 = c(3, 4) )
  • 如果在句子中有相应的单词,我还需要将字典中单词的长度放入 dt 列“word_length”。假设每个句子可能只有一个来自 dict 的单词。长度只是 dict 中一个单词的长度,或者只是每个 dict 单词的 dict 列中的一个数字。
  • 我已根据您的新数据编辑了我的解决方案。
  • 感谢您的帮助!但问题是,我无法清理字典,我必须从字典中搜索整个每个阶段。短语可能包括字母、数字点等,但我需要完整的短语。唯一的分隔符是逗号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 2018-03-29
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
相关资源
最近更新 更多