如何从输入用户获得最多重复的字母?

  • 本文关键字:用户 r
  • 更新时间 :
  • 英文 :

a <- as.character(readline(" Please input a text:    "))
most_repeated_character <- function(x) {
a <- gsub("\s+", "", a)
lets <- strsplit(a, "")[[1]]
tbl <- sort(table(lets), decreasing=TRUE)
print(paste("most frequently occurring: (", names(tbl)[1], ", ", tbl[[1]], ")"))
print(paste("second most frequently occurring: (", names(tbl)[2], ", ", tbl[[2]], 
")"))
}
most_repeated_character(a)

我只想得到重复次数最多的字母,而不是字符。例如,如果我输入"Hello world &&&& &&quot;,我会得到'l'作为重复次数最多的,而不是'&'。

对于非字母字符使用正则表达式

非字母字符的正则表达式为[^a-zA-Z]

尝试改变:

a <- gsub("\s+", "", a)

:

a <- gsub("[^a-zA-Z]", "", a)

另一个可能的错误是,当您输入大写时和/或小写那么,首先您必须标准化输入,使用如下函数:tolower()toupper()

librabry(tidyverse)
a <- "HolA MaMA &&&& $$$$ %%%%"
most_repeated_character <- function(x) {
x <- gsub("[^a-zA-Z]", "", x) %>% 
tolower() %>% 
strsplit("") %>% 
table() %>% 
sort(decreasing = TRUE)

print(paste("most frequently occurring: (", names(x)[1], ", ", x[[1]], ")"))
print(paste("second most frequently occurring: (", names(x)[2], ", ", x[[2]], ")"))
}
most_repeated_character(a)

最新更新