将两个单词的第一个字母大写为两个单词的字符串

时间:2011-06-15 21:44:44

标签: r string title-case

假设我有两个单词的字符串,我想要大写 他们两个。

name <- c("zip code", "state", "final count")

Hmisc包有一个函数capitalize,它将第一个单词大写,但我不确定 如何让第二个词大写。 capitalize的帮助页面并不表示它可以执行该任务。

library(Hmisc)
capitalize(name)
# [1] "Zip code"    "State"       "Final count"

我想得到:

c("Zip Code", "State", "Final Count")

三字串怎么样:

name2 <- c("I like pizza")

14 个答案:

答案 0 :(得分:156)

执行大写的基本R函数是toupper(x)。从?toupper的帮助文件中可以找到您需要的功能:

simpleCap <- function(x) {
  s <- strsplit(x, " ")[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2),
      sep="", collapse=" ")
}

name <- c("zip code", "state", "final count")

sapply(name, simpleCap)

     zip code         state   final count 
   "Zip Code"       "State" "Final Count" 

编辑这适用于任何字符串,无论字数如何:

simpleCap("I like pizza a lot")
[1] "I Like Pizza A Lot"

答案 1 :(得分:113)

标题案例中还有一个内置的 base-R解决方案

tools::toTitleCase("demonstrating the title case")
## [1] "Demonstrating the Title Case"

library(tools)
toTitleCase("demonstrating the title case")
## [1] "Demonstrating the Title Case"

答案 2 :(得分:91)

匹配从开始^开始或在空格[[:space:]]之后开始的正则表达式,后跟字母字符[[:alpha:]]。全局(gsub中的g)用匹配的开头或空格以及匹配的字母字符\\1\\U\\2的大写版本替换所有这些出现。这必须使用perl风格的正则表达式匹配来完成。

gsub("(^|[[:space:]])([[:alpha:]])", "\\1\\U\\2", name, perl=TRUE)
# [1] "Zip Code"    "State"       "Final Count"

对于gsub()的替换参数的更多详细信息,\\1说'使用匹配第一个子表达式的x部分',即x的部分1}}匹配(^|[[:spacde:]])。同样,\\2表示使用匹配第二个子表达式x的{​​{1}}部分。 ([[:alpha:]])是使用\\U启用的语法,意味着使下一个字符为大写。因此,对于“邮政编码”,perl=TRUE为“Zip”,\\1为“代码”,\\2为“代码”,\\U\\2为“邮政编码”。< / p>

\\1\\U\\2页面有助于理解正则表达式?regexp,以便将各种内容组合在一起。

答案 3 :(得分:75)

stringi

使用此功能
stri_trans_totitle(c("zip code", "state", "final count"))
## [1] "Zip Code"      "State"       "Final Count" 

stri_trans_totitle("i like pizza very much")
## [1] "I Like Pizza Very Much"

答案 4 :(得分:31)

替代:

library(stringr)
a = c("capitalise this", "and this")
a
[1] "capitalise this" "and this"       
str_to_title(a)
[1] "Capitalise This" "And This"   

答案 5 :(得分:21)

尝试:

require(Hmisc)
sapply(name, function(x) {
  paste(sapply(strsplit(x, ' '), capitalize), collapse=' ')
})

答案 6 :(得分:16)

来自?toupper的帮助页面:

.simpleCap <- function(x) {
    s <- strsplit(x, " ")[[1]]
    paste(toupper(substring(s, 1,1)), substring(s, 2),
          sep="", collapse=" ")
}


> sapply(name, .simpleCap)

zip code         state   final count 
"Zip Code"       "State" "Final Count"

答案 7 :(得分:9)

BBmisc现在包含函数capitalizeStrings

library("BBmisc")
capitalizeStrings(c("the taIl", "wags The dOg", "That Looks fuNny!")
    , all.words = TRUE, lower.back = TRUE)
[1] "The Tail"          "Wags The Dog"      "That Looks Funny!"

答案 8 :(得分:6)

使用子字符串和正则表达式的替代方法:

substring(name, 1) <- toupper(substring(name, 1, 1))
pos <- regexpr(" ", name, perl=TRUE) + 1
substring(name, pos) <- toupper(substring(name, pos, pos))

答案 9 :(得分:2)

你也可以使用蛇形包:

install.packages("snakecase")
library(snakecase)

name <- c("zip code", "state", "final count")
to_upper_camel_case(name, sep_out = " ")
#> [1] "Zip Code"    "State"       "Final Count"

https://github.com/Tazinho/snakecase

答案 10 :(得分:2)

StrCap 中使用 DescTools 的另一个版本

Text = c("This is my phrase in r", "No, this is not my phrase in r")

DescTools::StrCap(Text) # Default only first character capitalized
[1] "This is my phrase in r"         "No, this is not my phrase in r"

DescTools::StrCap(Text, method = "word") # Capitalize each word
[1] "This Is My Phrase In R"        "No This Is Not My Phrase In R"

> DescTools::StrCap(Text, method = "title") # Capitalize as in titles
[1] "This Is My Phrase in R"         "No, This Is Not My Phrase in R"

答案 11 :(得分:1)

这为所有主要词汇提供了大写字母

x_max = np.max(np.mean(trench_filter,axis=0).nonzero())
x_min = np.min(np.mean(trench_filter,axis=0).nonzero())
y_max = np.max(np.mean(trench_filter,axis=1).nonzero())
y_min = np.min(np.mean(trench_filter,axis=1).nonzero())

答案 12 :(得分:0)

此处对已接受的答案进行了一点改进,避免了必须使用sapply()。还会强制降低非首字符。

titleCase <- Vectorize(function(x) {
  
  # Split input vector value
  s <- strsplit(x, " ")[[1]]
  
  # Perform title casing and recombine
  ret <- paste(toupper(substring(s, 1,1)), tolower(substring(s, 2)),
        sep="", collapse=" ")
  
  return(ret)
  
}, USE.NAMES = FALSE)


name <- c("zip CODE", "statE", "final couNt")

titleCase(name)

#> "Zip Code"       "State" "Final Count" 

答案 13 :(得分:0)

✓ 一行
✓ 一项现有功能;没有新包
✓ 处理列表/所有单词
✓ 大写第一个字母并降低单词的其余部分:

name <- c("zip CODE", "statE", "final couNt")
gsub("([\\w])([\\w]+)", "\\U\\1\\L\\2", name, perl = TRUE)
[1] "Zip Code"    "State"       "Final Count"

如果你打算经常使用它,我想你可以用它做一个包装函数:

capFirst <- function(x) gsub("([\\w])([\\w]+)", "\\U\\1\\L\\2", x, perl = TRUE)
capFirst(name)