[英]How to reverse a sentence in R?
I want a function that takes a string (NOT a vector) and reverses the words in that string. 我想要一个带字符串(不是向量)并反转该字符串中的单词的函数。
For example, 例如,
rev_sentence("hi i'm five")
## [1] "five i'm hi"
I have a function that reverses individual characters, but not something that will reverse a string that's essentially a sentence. 我有一个函数可以反转单个字符,但不能反转一个基本上是句子的字符串。
In R
, We can use strsplit
to split at one or more spaces and then reverse the elements and paste
it together 在
R
,我们可以使用strsplit
在一个或多个空格处分割,然后反转元素paste
其paste
在一起
sapply(strsplit(str1, "\\s+"), function(x) paste(rev(x), collapse=" "))
#[1] "five i'm hi"
If there is only a single string, then 如果只有一个字符串,那么
paste(rev(strsplit(str1, "\\s+")[[1]]), collapse= " ")
#[1] "five i'm hi"
In Python
, the option would be to split
and join
after reversing ( [::-1]
) 在
Python
,选项是在反转后split
和join
( [::-1]
)
" ".join("hi i'm five".split()[::-1])
#"five i'm hi"
Or use the reversed
或者使用
reversed
" ".join(reversed("hi i'm five".split()))
#"five i'm hi"
str1 <- "hi i'm five"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.