R语言 如何从输入用户那里得到最多的重复字母?

3df52oht  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(156)
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 &&&&",我会得到”l“作为重复次数最多的字母,而不是”&“。

li9yvcax

li9yvcax1#

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

非字母字符的正则表达式为[^a-zA-Z]
尝试更改:

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

至:

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

1l5u6lss2#

另一个可能的错误是,当您输入大写和/或小写单词时,首先必须使用以下函数标准化输入: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)

相关问题