Making gsub only replace entire words?

后端 未结 2 830
我在风中等你
我在风中等你 2020-12-17 20:41

(I\'m using R.) For a list of words that\'s called \"goodwords.corpus\", I am looping through the documents in a corpus, and replacing each of the words on the list \"goodwo

2条回答
  •  时光取名叫无心
    2020-12-17 20:56

    Use \b to indicate a word boundary:

    > text <- "good night goodnight"
    > gsub("\\bgood\\b", paste("good", 1234), text)
    [1] "good 1234 night goodnight"
    

    In your loop, something like this:

    for (word in goodwords.corpus){
      patt <- paste0('\\b', word, '\\b')
      repl <- paste(word, "1234")
    
      test <-gsub(patt, repl, test)
    }
    

提交回复
热议问题