如何在R中颠倒一个句子? [英] How to reverse a sentence in R?

查看:79
本文介绍了如何在R中颠倒一个句子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个函数,它接受一个字符串(不是向量)并反转该字符串中的单词.

I want a function that takes a string (NOT a vector) and reverses the words in that string.

例如

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.

推荐答案

R 中,我们可以使用 strsplit 在一个或多个空格处进行拆分,然后将元素反转和粘贴一起

In R, We can use strsplit to split at one or more spaces and then reverse the elements and paste it together

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"

<小时>

Python中,选项是在反转后splitjoin ([::-1]>)


In Python, the option would be to split and join after reversing ([::-1])

" ".join("hi i'm five".split()[::-1])
#"five i'm hi"

或者使用反转

" ".join(reversed("hi i'm five".split()))
#"five i'm hi"

数据

str1 <- "hi i'm five"

这篇关于如何在R中颠倒一个句子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆