【问题标题】:substitute words in a column替换列中的单词
【发布时间】:2019-03-29 09:46:52
【问题描述】:
a <- data.frame(text = c("hello <firstname> what do you wish to order today?", "I don't understand this. Can you repeat"))

我想用空白替换 - “你好”和“你能不能重复一下”,以便我得到剩余的部分文本。

如何给出我想用空白替换的特定单词列表。 这里的具体词是“你好”和“你能重复一下吗”。像这样,我的数据框中有很多词。

数据框中的预期输出:

[1] what do you wish to order today?

[2] I don't understand this.

【问题讨论】:

  • 请修正你的例子。它抛出错误。也许你正在寻找这个trimws(gsub('hello|can you repeat', '', tolower(a$text))) 虽然我不确定&lt;firstname&gt; 发生了什么

标签: r


【解决方案1】:

gsub 的一种方式:

#add the words to remove in an atomic vector
to_remove <- c('hello', 'Can you repeat')
#paste the words together and remove with gsub
gsub(paste(to_remove, collapse = '|'), ' ', a$text)
#[1] "  <firstname> what do you wish to order today?"
#[2] "I don't understand this.  "

根据@Sotos 的评论,在处理文本时,最好将文本小写并去掉尾随空格:

trimws(paste(to_remove, collapse = '|'), '', tolower(a$text)))

【讨论】:

  • 几个建议。将所有内容保留/转换为小写可能会更好。您也可以将所有内容包装在 trimws 中以消除前导/尾随空格 - 请参阅我上面的评论
  • @Sotos 是的,我都同意。这是处理文本时最安全的技术。我想我只想展示 OP 所要求的答案。我会补充的。
【解决方案2】:

您可以使用一个名为 gsub 的函数。它查看给定模式的字符串,然后替换为所需的输出。

gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
    fixed = FALSE, useBytes = FALSE)

例子:

gsub("hello", "", a$text)

然后,如果您愿意,可以将输出保存为新列或新变量。

gsub 区分大小写还有一些其他的东西,但可以在here 找到。这也有一些额外的例子。

【讨论】:

    【解决方案3】:

    gsub 解决方案也可以,这是一个 tidyverse 解决方案。

    require(tidyverse)
    b <- a %>% mutate(
        text_new = str_remove_all(text, c("hello <firstname>", "Can you repeat"))
      )
    b
    

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 2022-12-10
      • 2015-03-02
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多