【问题标题】:How to find the exact match in for loop using gsub?如何使用 gsub 在 for 循环中找到完全匹配?
【发布时间】:2019-08-19 23:29:26
【问题描述】:

我只想替换数据数据框中的确切术语。在下面的示例中,我试图用 xx 替换单词 java,但它替换了 javascript 以及 xxscript。

data$new
[1] "xxscript is a statically typed and xx py is a dynamically typed"
[2] "xx is a programming language" 
data = data.frame("word"=c('python', 'java'), 
                    "description"=c('Javascript is a statically typed and Python py is a dynamically typed',
                                    'java is a programming language'), stringsAsFactors = FALSE)

ll <- as.list(data$word)
data$new <- data$description
for(i in seq_len(nrow(data))) for(j in seq_along(ll)) {
    data$new[i] <- gsub(ll[j], "xx", data$new[i],ignore.case = T)
}
data$new

我希望只替换确切的条款。

【问题讨论】:

    标签: r regex pattern-matching gsub exact-match


    【解决方案1】:

    使用单词边界\\b

    gsub("\\bjava\\b", "xx", c("my java is", "this javascript is"))
    #[1] "my xx is"           "this javascript is"
    

    你可能想要

    ll <- as.list(data$word)
    data$new <- data$description
    for(i in seq_len(nrow(data))) for(j in seq_along(ll)) {
        data$new[i] <- gsub(paste0("\\b", ll[j], "\\b"), "xx", data$new[i],ignore.case = T)
    }
    

    【讨论】:

      【解决方案2】:

      您可以通过将单词列表与或|sub 连接向量来删除两个循环:

      data$new <- sub(paste0("\\b", ll, "\\b", collapse="|"), "xx", data$description, ignore.case = T)
      

      要匹配单词,您可以使用@d-b 已经显示的边界\\b

      【讨论】:

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