如何提取数据框列中的所有匹配模式(字符串中的单词?)>

问题描述 投票:0回答:1

我有两个数据框。一个(txt.df

)有一列,我想从(text)中提取短语。另一个(wrd.df)的列中包含短语(phrase)。两者都是具有复杂文本和字符串的大数据框,但可以说:
txt.df <- data.frame(id = c(1, 2, 3, 4, 5),
                     text = c("they love cats and dogs", "he is drinking juice", 
                              "the child is having a nap on the bed", "they jump on the bed and break it",
                              "the cat is sleeping on the bed"))


wrd.df <- data.frame(label = c('a', 'b', 'c', 'd', 'e', 'd'),
                     phrase = c("love cats", "love dogs", "juice drinking", "nap on the bed", "break the bed",
                              "sleeping on the bed"))

我最终需要的是txt.df

,其中另一列包含所检测到的短语的标签。

我尝试在wrd.df中创建一列,在其中标记了这样的短语

wrd.df$token <- sapply(wrd.df$phrase, function(x) unlist(strsplit(x, split = " ")))

然后尝试编写一个自定义函数,以使用grepl / str_detect将其应用于令牌列取得全部正确的名称(标签)

Extract.Fun <- function(text, df, label, token){
  for (i in token) {
  truefalse[i] <- sapply(token[i], function (x) grepl(x, text))
  truenames[i] <- names(which(truefalse[i] == T))
  removedup[i] <- unique(truenames[i])
  return(removedup)
}

然后在我的txt.df $ text上应用此自定义函数,以在其标签上添加新列。

txt.df$extract <- sapply(txt.df$text, function (x) Extract.Fun(x, wrd.df, "label", "token"))

但是我对自定义功能不满意,而且确实很卡住。我将不胜感激任何帮助。附言如果我还可以进行部分匹配,例如“喝果汁”和“打破床”,那将是非常好的。

我有两个数据框。一个(txt.df)有一列,我想从(文本)中提取短语。另一个(wrd.df)有一列包含短语(短语)。都是复杂的大数据框...

r for-loop string-matching partial-matches
1个回答
0
投票

如果需要匹配确切的短语,则需要regex_join()包中的fuzzyjoin

© www.soinside.com 2019 - 2024. All rights reserved.