【发布时间】:2020-06-02 09:52:50
【问题描述】:
我想随机打乱句子中组成单词的字母顺序。我可以对单个单词进行改组,例如:
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"
这显然不是正确的结果。如何随机打乱句子中每个单词的字母顺序?
【问题讨论】:
-
骗子:Better way to shuffle elements of a string in R。因此,例如
stri_rand_shuffle(stri_split_fixed(b, " ")[[1]]) -
这是一个超酷的解决方案,你一定要发布它。