【发布时间】:2021-04-06 17:20:29
【问题描述】:
有没有办法使用 str_detect 函数检测单词的第一个字母是否是辅音?
例如:如果我有“房子”这个词,我希望输出为“真”。
我尝试了以下代码,但它不起作用。
word<-c("house")
str_detect(word, "^(-[aeiou])")
【问题讨论】:
标签: r
有没有办法使用 str_detect 函数检测单词的第一个字母是否是辅音?
例如:如果我有“房子”这个词,我希望输出为“真”。
我尝试了以下代码,但它不起作用。
word<-c("house")
str_detect(word, "^(-[aeiou])")
【问题讨论】:
标签: r
我们可以将除 aeiou 之外的所有其他字符与 ^ 匹配在 [] 中。 [ 外的 ^ 表示字符串的开头
library(stringr)
str_detect(word, "^[^aeiou]")
#[1] TRUE
或者另一种选择是否定 (!)
!str_detect(word, "^[aeiou]")
或者也可以使用
substr(word, 1, 1) %in% setdiff(letters, c('a', 'e', 'i', 'o', 'u'))
#[1] TRUE
或者用grepl 来自base R
grepl('^[^aeiou]', word)
#[1] TRUE
【讨论】:
为什么不直接使用字符串开始标记^和元音类呢?如果匹配返回 FALSE,你就知道它是辅音:
str_detect(word, "^[aeiou]")
[1] FALSE
【讨论】:
为了好玩,我创建了一个自己的函数IsCons
IsCons <- function(x) {
lower_consonant <- c("b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z")
upper_consonant <- toupper(consonant)
a <- substring(x, 1, 1)
a %in% lower_consonant | a %in% upper_consonant
}
检查自己的功能
word<-c("Ant", "House", "ant", "house")
IsCons(word)
输出
> IsCons(word)
[1] FALSE TRUE FALSE TRUE
万岁!
【讨论】: