【问题标题】:Is there an R function for selecting words that end with a specific character?是否有用于选择以特定字符结尾的单词的 R 函数?
【发布时间】:2023-04-10 18:37:01
【问题描述】:

我是一个困惑的语言学家,试图使用 R 从 twitter 收集数据。 我一直在使用 twitteR 包,它在使用固定字符串时效果很好,但我想要求它获取包含“querendo + 不定式动词”的推文。在葡萄牙语中,不定式动词总是以字符 'r' 结尾。如何查询以特定字符结尾的单词?

searchtwitteR(" ", n = 1000, lang = pt, locate = Brazil)

【问题讨论】:

    标签: r linguistics


    【解决方案1】:

    有很多方法可以做到这一点。将words 视为向量

    words <- c('rock', 'tempr', 'infinitr', 'end', 'twitter')
    

    在基础 R 中:

    1) 使用endsWith

    words[endsWith(words, 'r')]
    #[1] "tempr"    "infinitr" "twitter" 
    

    2) 使用grep

    grep('r$', words, value = TRUE)
    

    3)grepl

    words[grepl('r$', words)]
    

    使用stringr

    library(stringr)
    

    1) str_detect

    words[str_detect(words, 'r$')]
    

    2) str_subset

    str_subset(words, 'r$')
    

    【讨论】:

      【解决方案2】:

      我们可以从stringi使用stri_detect

      library(stringi)
      words[stri_detect(words, regex = 'r$')]
      #[1] "tempr"    "infinitr" "twitter" 
      

      或与substring 来自base R

      words[substring(words, nchar(words)) == 'r']
      

      数据

      words <- c('rock', 'tempr', 'infinitr', 'end', 'twitter')
      

      【讨论】: