【问题标题】:Multiple Text String Modifications in RR中的多个文本字符串修改
【发布时间】:2021-02-22 21:30:12
【问题描述】:

我有多个字符串存储在一个原子向量中:

v <- c("The kat ran up the tree", "The dogg ran up the tree", "The squirrrel run up the tree")

我想更正拼写错误:

v <- gsub('kat', 'cat', v)
v <- gsub('dogg', 'dog', v)
v <- gsub('squirrel', 'squirrrel', v)

但是我不喜欢重复的代码。有没有办法做到这一点:

v1 <- c('kat', 'dogg', 'squirrrel')
v2 <- c('cat', 'dog', 'squirrel')

v <- gsub(v1, v2, v)

【问题讨论】:

    标签: r text nlp


    【解决方案1】:

    最简单的选项是 str_replace_all 并传递 named vectorlist

    library(stringr)
    str_replace_all(v, setNames(v2, v1))
    

    -输出

    #[1] "The cat ran up the tree"     
    #[2] "The dog ran up the tree"  
    #[3]    "The squirrel run up the tree"
    

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多