【问题标题】:For each word in a string, check if it is part of another string of words对于字符串中的每个单词,检查它是否是另一个单词字符串的一部分
【发布时间】:2020-03-22 02:58:17
【问题描述】:

我有一个DT如下:

DT <- fread("
ID  Sentence_1                  Sentence_2                        iso3c   year
1   This_is_an_example_sentence This_is_another_example_sentence  ARG     1983
2   The_dog_walks_in_the_park   This_is_another_example_sentence  ARG     1983
5   The_dog_walks_in_the_park   A_frisby_is_thrown_in_the_park    NLD     1984
6   I_like_soup                 A_frisby_is_thrown_in_the_park    NLD     1984",
header=TRUE)
DT$Sentence_1 <- gsub("_", " ", DT$Sentence_1)
DT$Sentence_2 <- gsub("_", " ", DT$Sentence_2)

我想检查Sentence_1 中的每个单词是否也存在于Sentence_2 中。我想将该查询的结果存储在单独的列中。

期望的输出:

DT <- fread("
ID  Sentence_1                  Sentence_2                        iso3c   year  matching_score
1   This_is_an_example_sentence This_is_another_example_sentence  ARG     1983  4
2   The_dog_walks_in_the_park   This_is_another_example_sentence  ARG     1983  0
5   The_dog_walks_in_the_park   A_frisby_is_thrown_in_the_park    NLD     1984  3
6   I_like_soup                 A_frisby_is_thrown_in_the_park    NLD     1984  0",
header=TRUE)

这样做最有效的方法是什么?

【问题讨论】:

  • 你已经尝试了什么?
  • 我的意思是,我正在考虑一些复杂的事情,我首先将两个字符串分成单独的单词,将它们放入一个向量中,然后检查连接向量有多少重复项。但我想我希望我不是第一个尝试这个的人,并且那里有一些更复杂的解决方案。我对字符串操作等不是很熟悉。
  • 另外我的数据集真的很大,我正在寻找最有效的方法。

标签: r string parsing data.table character


【解决方案1】:
DT[, `:=`(s1l = strsplit(Sentence_1, "_"), s2l = strsplit(Sentence_2, "_"))]
DT[, matching_score := sum(s1l[[1]] %in% s2l[[1]]), by = ID][, !c("s1l", "s2l")]
DT



   ID                  Sentence_1                       Sentence_2 iso3c year matching_score
1:  1 This_is_an_example_sentence This_is_another_example_sentence   ARG 1983              4
2:  2   The_dog_walks_in_the_park This_is_another_example_sentence   ARG 1983              0
3:  5   The_dog_walks_in_the_park   A_frisby_is_thrown_in_the_park   NLD 1984              3
4:  6                 I_like_soup   A_frisby_is_thrown_in_the_park   NLD 1984              0

【讨论】:

  • 有没有办法让这个答案中的大写无关紧要(dog = Dog)?
  • @Tom,是的,例如,您可以在拆分字符串之前将它们转换为全小写。示例:s1l = strsplit(tolower(Sentence_1), "_").
猜你喜欢
  • 2019-12-29
  • 2015-08-07
  • 2020-03-10
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 2012-05-20
  • 2021-01-22
  • 2014-08-09
相关资源
最近更新 更多