【发布时间】:2012-12-13 06:31:44
【问题描述】:
给定以下代码:
list = c("the", "at", "ok")
paragraph = "the cat ath the hat is ok"
如何从“段落”中删除列表中的所有单词?
我试过了:
gsub(list, '', paragraph)
但仅删除了列表的第一项。我知道这不应该很复杂,但这仍然让我感到困惑。我也想避免使用 for 循环,但 apply 系列应该没问题。
【问题讨论】:
给定以下代码:
list = c("the", "at", "ok")
paragraph = "the cat ath the hat is ok"
如何从“段落”中删除列表中的所有单词?
我试过了:
gsub(list, '', paragraph)
但仅删除了列表的第一项。我知道这不应该很复杂,但这仍然让我感到困惑。我也想避免使用 for 循环,但 apply 系列应该没问题。
【问题讨论】:
"(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 "
【讨论】:
for 循环中一次处理一个单词的速度相同。无论如何,这确实工作,所以它至少有 that 这样做;)
paragraph 包含多个字符串,否则您可能不会使用apply。顺便说一句,不要调用你的变量list ;)
for 循环”:)