随机打乱句子中单词中的字母

Randomly shuffle letters in words in sentences

我想随机打乱句子中组成单词的字母顺序。我可以对单个单词进行改组,例如:

a <- "bach"
sample(unlist(str_split(a, "")), nchar(a))
[1] "h" "a" "b" "c"

但我没能对句子做到这一点,例如:

b <- "bach composed fugues and cantatas"

到目前为止我尝试了什么:

拆分成单词:

b1 <- str_split(b, " ")
[[1]]
[1] "bach"     "composed" "fugues"   "and"      "cantatas"

计算每个单词的字符数:

n <- lapply(b1, function(x) nchar(x))
n
[[1]]
[1] 4 8 6 3 8

b1 中的单词拆分为单个字母:

b2 <- str_split(unlist(str_split(b, " ")), "")
b2
[[1]]
[1] "b" "a" "c" "h"    
[[2]]
[1] "c" "o" "m" "p" "o" "s" "e" "d"    
[[3]]
[1] "f" "u" "g" "u" "e" "s"    
[[4]]
[1] "a" "n" "d"    
[[5]]
[1] "c" "a" "n" "t" "a" "t" "a" "s"

根据以上将每个单词中的字母打乱:

lapply(b2, function(x) sample(unlist(x), unlist(n), replace = T))
[[1]]
[1] "h" "a" "c" "b"   
[[2]]
[1] "o" "p" "o" "s"   
[[3]]
[1] "g" "s" "s" "u"    
[[4]]
[1] "d" "d" "a" "d"   
[[5]]
[1] "c" "n" "s" "a"

这显然不是正确的结果。如何随机打乱句子中每个单词的字母顺序?

b2 之后,您可以使用 sample 随机打乱字符,然后将单词粘贴回去。

paste0(sapply(b2, function(x) paste0(sample(x), collapse = "")), collapse = " ")
#[1] "bhac moodscpe uefusg and tsatnaac"

请注意,如果您希望输出与使用 replace = FALSE 的输入长度相同,则无需在 sample 中提及 size