【问题标题】:gsub a list of words in a paragraphgsub 段落中的单词列表
【发布时间】:2012-12-13 06:31:44
【问题描述】:

给定以下代码:

list = c("the", "at", "ok")
paragraph = "the cat ath the hat is ok"

如何从“段落”中删除列表中的所有单词?

我试过了:

gsub(list, '', paragraph)

但仅删除了列表的第一项。我知道这不应该很复杂,但这仍然让我感到困惑。我也想避免使用 for 循环,但 apply 系列应该没问题。

【问题讨论】:

    标签: regex r


    【解决方案1】:

    "(the|at|ok)" 模式将匹配列表中出现的任何字符串。

    不过,这听起来像是您想要匹配那些实际的单词而不是它们所属的单词(即匹配“the”而不是“then”、“at”而不是“rattle”等)如果在这种情况下,您可以改用"\\b(the|at|ok)\\b" 模式(其中"\\b" 是匹配单词边界的模式)。

    您可以使用paste0() 从任意匹配词向量构造所需的模式:

    list <- c("the", "at", "ok")
    paragraph <- "the cat ath the hat is ok"
    
    ## Construct the regular expression
    pat <- paste0("\\b(", paste0(list, collapse="|"), ")\\b")    
    pat
    # [1] "\\b(the|at|ok)\\b"
    
    ## Use it
    gsub(pat, "", paragraph)
    # [1] " cat ath  hat is "
    

    【讨论】:

    • 感谢您的回答。有更自然的方法吗?
    • @user1103294 我想我们会发现的!在相关说明中,我很想知道这是否更快、更慢或与在for 循环中一次处理一个单词的速度相同。无论如何,这确实工作,所以它至少有 that 这样做;)
    • @user1103294 josh 的反应非常自然。除非paragraph 包含多个字符串,否则您可能不会使用apply。顺便说一句,不要调用你的变量list ;)
    • @anthonydamico 我认为明确地使用某种循环是一种更自然的方式。这就是我认为他的回答很聪明的部分原因,但他没有。
    • @user1103294 你确实说过,“请不要使用for 循环”:)
    猜你喜欢
    • 2021-05-16
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多