【问题标题】:Removing duplicate words in a string in R删除R中字符串中的重复单词
【发布时间】:2013-12-15 12:34:50
【问题描述】:

只是为了帮助那些在他尝试过的代码请求和其他 cmets 之后自愿删除他们的问题的人。让我们假设他们尝试过这样的事情:

str <- "How do I best try and try and try and find a way to to improve this code?"
d <- unlist(strsplit(str, split=" "))
paste(d[-which(duplicated(d))], collapse = ' ')

并想学习更好的方法。那么从字符串中删除重复单词的最佳方法是什么?

【问题讨论】:

  • 这似乎是一个很好的解决方案,尽管您可能希望 gsub 去掉标点符号,否则例如“代码?”在例句中不会被标记为早期独立“代码”的副本。

标签: r duplicates


【解决方案1】:

如果您仍然对替代解决方案感兴趣,可以使用unique,这会稍微简化您的代码。

paste(unique(d), collapse = ' ')

根据 Thomas 的评论,您可能确实想删除标点符号。 R 的gsub 有一些不错的内部模式,您可以使用它来代替严格的正则表达式。当然,如果你想做一些更精细的正则表达式,你总是可以指定特定的实例。

d <- gsub("[[:punct:]]", "", d)

【讨论】:

    【解决方案2】:

    不需要额外的包

    str <- c("How do I best try and try and try and find a way to to improve this code?",
             "And and here's a second one one and not a third One.")
    

    原子函数:

    rem_dup.one <- function(x){
      paste(unique(tolower(trimws(unlist(strsplit(x,split="(?!')[ [:punct:]]",fixed=F,perl=T))))),collapse = " ")
    }
    rem_dup.one("And and here's a second one one and not a third One.")
    

    矢量化

    rem_dup.vector <- Vectorize(rem_dup.one,USE.NAMES = F)
    rem_dup.vector(str)
    

    结果

    "how do i best try and find a way to improve this code" "and here's a second one not third" 
    

    【讨论】:

      【解决方案3】:

      删除除任何特殊字符外的重复单词。使用这个功能

      rem_dup_word <- function(x){
      x <- tolower(x)
      paste(unique(trimws(unlist(strsplit(x,split=" ",fixed=F,perl=T)))),collapse = 
      " ")
      }
      

      输入数据:

      duptest <- "Samsung WA80E5LEC samsung Top Loading with Diamond Drum, 6 kg 
      (Silver)"
      
      rem_dup_word(duptest)
      

      输出:samsung wa80e5lec top loading with diamond drum 6 kg (silver)

      它将“Samsung”和“SAMSUNG”视为重复

      【讨论】:

        【解决方案4】:

        我不确定字符串大小写是否值得关注。此解决方案使用 qdap 和附加组件 qdapRegex 包,以确保标点符号和开头的字符串大小写不会干扰删除但得到维护:

        str <- c("How do I best try and try and try and find a way to to improve this code?",
            "And and here's a second one one and not a third One.")
        
        library(qdap)
        library(dplyr) # so that pipe function (%>% can work) 
        
        str %>% 
            tolower() %>%
            word_split() %>% 
            sapply(., function(x) unbag(unique(x))) %>% 
            rm_white_endmark() %>%  
            rm_default(pattern="(^[a-z]{1})", replacement = "\\U\\1") %>%
            unname()
        
        ## [1] "How do i best try and find a way to improve this code?"
        ## [2] "And here's a second one not third."
        

        【讨论】:

        • 什么是 word_split() 函数,当尝试运行此代码时,它在 word_split() 上抛出错误。
        • 您是否安装了 qdap 软件包?
        • !啊。我得到了它。我没有注意到我对 rJava 包有问题,这是 qdap 的一种依赖项。谢谢@Rinker。
        猜你喜欢
        • 2012-03-14
        • 1970-01-01
        • 2013-08-11
        • 2013-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多