繁体   English   中英

R:确定两个不同数据帧的两个文本字符串之间的第一,第二,第三,第四匹配

[英]R: Identify 1st, 2nd, 3rd, 4th match between two text strings of two different dataframes

是否有任何R包来标识两个不同数据帧的两个文本字符串列之间的第一,第二,第三,第四匹配的位置(行索引)?

例如:

我有以下数据框:

dataframe: simpletext

row text
1   does he go to that bar or for shopping?
2   where was that bar that I wanted?
3   I would like to go to the opera instead for shopping


dataframe: keywords

row  word
1    shopping
2    opera
3    bar

我想要找到的是simpletext $ text [1]的第一个匹配项是关键字$ word [3]

simpletext $ text [1]的第二个匹配项是关键字$ word [1],依此类推,对于每一行或simpletext

您可能会从以下内容开始:

library(tidyverse)
find_locations <- function(word, text) {
  bind_cols(
    data_frame(
      word = word,
      text = text
    ),
    as_data_frame(str_locate(text, word))
  )
}

map_df(keywords$word, find_locations, text = simpletext$text)

您可以使用regexprgrep系列)功能:

keywords = rbind("shopping","opera","bar")
simpletext = rbind("does he go to that bar or for shopping?",
                   "where was that bar that I wanted?",
                   "I would like to go to the opera instead for shopping")

text_match <- function(text,keywords)
{
  # check all keywords for matching
  matches <- vapply(keywords[1:length(keywords)], function(x) regexpr(x,text)[1], FUN.VALUE=1) 
  # sort matched keywords in order of appearance
  sorted_matches <- names(sort(matches[matches>0])) 
  # return indices of sorted matches
  indices <- vapply(sorted_matches, function(x) which(keywords == x),FUN.VALUE=1) 
  return (indices)
}

其中regexpr(x,text)[1]返回xtext中的第一个匹配项的位置,如果没有则返回-1

结果如下:

text_match(simpletext[1],keywords)
#bar shopping 
#3        1 
text_match(simpletext[2],keywords)
# bar 
# 3
text_match(simpletext[3],keywords)
# opera shopping 
# 2        1 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM