R从句子中得到N个单词作为字符串

时间:2017-11-22 12:45:49

标签: r substring

在R中我怎么能写一个函数给定一个句子我可以传递一个整数参数,它将结束单词作为一个字符串返回

EG

sentence <- "The quick brown fox jumps over the lazy dog"
result <- get_words(sentence, 2)

结果应该等于"lazy dog"

该函数应该包含guard子句,如果请求的总单词超过句子中的单词,则返回最后一个单词

3 个答案:

答案 0 :(得分:1)

您可以使用stringr库。

library(stringr)

sentence <- "The quick brown fox jumps over the lazy dog"
word(sentence, start = -2, end = -1)

在tyluRp的建议之后编辑。

答案 1 :(得分:1)

// Example1
[CustomAuthAttribute]
public MyResponse get(string param1, string param2)
{
    ...
}
// in the prev example I would like to be able to identify the
// method from within the CustomAuthAttribute code


// Example2
[CustomAuthAttribute(MethodName = "mycontroller/get")]
public MyResponse get(string param1, string param2)
{
    ...
}
// in this example I pass the controller/method names to the
// CustomAuthAttribute code

答案 2 :(得分:1)

stringi解决方案(stringr::word()过度杀伤并使用了比此更多stringi个功能。stringr障碍包裹stringi功能):

library(stringi)

sentence <- "The quick brown fox jumps over the lazy dog"

tail(stri_extract_all_words(sentence)[[1]], 2)
## [1] "lazy" "dog" 

stri_join(tail(stri_extract_all_words(sentence)[[1]], 2), collapse=" ")
## [1] "lazy dog"

实际可读版本:

library(magrittr)

stri_extract_all_words(sentence)[[1]] %>% 
  tail(2) %>% 
  stri_join(collapse=" ")
## [1] "lazy dog"

它还使用了一种更好的,区域敏感的分词算法,它优于基础R。

相关问题