【问题标题】:replace string with a random character from a selection用选择中的随机字符替换字符串
【发布时间】:2017-10-22 19:58:26
【问题描述】:

如何获取字符串并将"."","" "(即点、逗号或空格)的每个实例替换为从c('|', ':', '@', '*') 中选择的一个随机字符?

假设我有一个这样的字符串

 Aenean ut odio dignissim augue rutrum faucibus. Fusce posuere, tellus eget viverra mattis, erat tellus porta mi, at facilisis sem nibh non urna. Phasellus quis turpis quis mauris suscipit vulputate. Sed interdum lacus non velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

为了得到一个随机字符,我们可以把这些字符当作一个向量,然后使用sample函数来选择一个。我假设首先我需要搜索点、逗号或空格,然后使用gsub 函数来替换所有这些?

【问题讨论】:

  • gsub('[., ]', sample(c('|',':','@','*'), 1), s) 其中s 是字符串。
  • 您希望(点、逗号或空格)始终替换为相同的字符吗?
  • @thelatemail 没有。只是 c('|',':','@','*') 中的任何人
  • @alistaire 替换为从字符向量中选择的一个随机字符。谢谢!

标签: r string random replace


【解决方案1】:

鉴于您的澄清,试试这个:

x <- c("this, is nice.", "nice, this is.")
gr <- gregexpr("[., ]", x)
regmatches(x,gr) <- lapply(lengths(gr), sample, x=c('|',':','@','*'))
x
#[1] "this|*is@nice:" "nice@|this*is:"

【讨论】:

    【解决方案2】:

    这是chartr的另一个选项

    pat <- paste(sample(c('|', ';', '@', '*'), 3), collapse="")
    chartr('., ', pat, x)
    #[1] "this|*is*nice;" "nice|*this*is;"
    

    数据

    x <- c("this, is nice.", "nice, this is.")
    

    【讨论】:

    • 与我的结果略有不同,因为它将每个原始字符匹配到相同的新字符,但我确实喜欢 chartr,因为我认为它是外包给 C 代码的。
    • @thelatemail 你是对的,它会匹配同一个字符。在阅读OP的问题时,不是很清楚
    • @akrun 对。感谢您的努力!这是另一种接近的好方法!
    猜你喜欢
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2017-03-08
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多