【问题标题】:How do I grab the word in a character column after two consecutive word matches in R?在 R 中连续两个单词匹配后,如何在字符列中抓取单词?
【发布时间】:2022-02-15 19:56:51
【问题描述】:

我有一个带有成对词向量的数据框“key_words”

key_words <- data.frame( c1 = ('word1','word2'), c2 = ('word3, word4'), c3 = ('word5','word6'))

我想在另一个数据框“x”的字符列“text”中搜索这些关键词对,其中每行可以是几句话。我想在 key_words 数据框中的列的两个连续匹配之后抓取单词,并将该值插入到与找到匹配的相同索引处的表中。例如,如果在 text[1] 中一个接一个地找到 'word1' 和 'word2',那么我想抓取 text[1] 中后面的单词并将其插入到 table[1] 中。

我尝试将“文本”中的每一行拆分为一个列表,用一个空格分隔,以便每个单词在每一行中都有自己的索引。我有以下想法,这似乎非常低效,我遇到了字符值 temp_list[k] 长度为 0 的问题。

x <- x %>% mutate(text = strsplit(text, " "))  
for (i in 1:ncol(key_words)) {
    word1 <- key_words[i, 1]
    word2 <- key_words[i, 2]
    for (j in 1:length(x$text)) {
      temp_list <- as.list(unlist(x$text[[j]]))
      for (k in 1:length(temp_list))
        if (word1 == temp_list[k]) {
          if (word2 == temp_list[k + 1]) {
            table$word_found[j] <- temp_list[k + 2]
          }
        }
    }

有没有更好的方法来做到这一点,或者我可以在文本列中搜索“word1 word2”并获取下一个可以是任意长度的单词?我是 R 和一般编码的新手,但我知道我应该避免这样的嵌套循环。任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: r loops nested-loops


    【解决方案1】:

    我建议你创建一个像这样的小函数,它返回出现在“w1 w2”对之后的单词

    get_word_after_pair <- function(text,w1,w2) {
      stringr::str_extract(text, paste0("(?<=\\b", w1, "\\s", w2, "\\b\\s)\\w*(?=\\b)"))
    }
    

    然后你就可以这样做了

    data.frame(
      lapply(key_words, function(x) get_word_after_pair(texttable$text,x[1],x[2]))
    )
    

    输入:

    keywords 是单词对列表,texttable 是带有列text 的框架)

    key_words <- list( pair1 = c('has','important'), pair2 = c('sentence','has'), pair3 = c('third','sentence'))
    
    texttable = data.frame(text=c("this sentence has important words that we must find",
                                  "this second sentence has important words to find",
                                  "this is the third sentence and it also has important words within")
    )
    

    输出:

      pair1     pair2 pair3
    1 words important  <NA>
    2 words important  <NA>
    3 words      <NA>   and
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多