【问题标题】:R get N words from a sentence as a stringR从一个句子中获取N个单词作为字符串
【发布时间】:2017-11-22 12:45:48
【问题描述】:

在 R 中,我如何编写一个函数,给定一个句子,我可以传递一个整数参数,将结束词作为字符串返回

EG

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

结果应该等于"lazy dog"

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

【问题讨论】:

    标签: r substring


    【解决方案1】:

    纯粹的stringi 解决方案(stringr::word() 是矫枉过正,比这使用更多的stringi 函数。stringr handicap-wraps 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 算法。

    【讨论】:

      【解决方案2】:
      sentence <- "The quick brown fox jumps over the lazy dog"
      paste(tail(strsplit(sentence, "\\s+")[[1]], 2), collapse=" ")
      

      【讨论】:

        【解决方案3】:

        您可以使用 stringr 库来做到这一点。

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

        根据 tyluRp 的建议编辑。

        【讨论】:

        • @akrun 刚好同时发帖,后来因为格式不好而编辑了。没有抄袭。
        • 你可以把它改成paste( word(sentence, -2:-1), collapse=' ') 反正有人投票反对我虽然我先发帖
        • word(sentence,-2) 返回 lazy 而不是 lazy dog,我错过了什么吗?
        • 这个应该修改为word(sentence, start = -2, end = -1)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        • 1970-01-01
        相关资源
        最近更新 更多