Programming

두 단어 문자열에서 두 단어의 첫 글자를 대문자로

procodes 2020. 6. 1. 20:20
반응형

두 단어 문자열에서 두 단어의 첫 글자를 대문자로


두 단어로 된 문자열이 있고 두 단어를 모두 대문자로 사용하려고한다고 가정하겠습니다.

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")

3 단어 문자열은 어떻습니까 :

name2 <- c("I like pizza")

대문자를 수행하는 기본 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"

빌드에서이 기본-R 솔루션 제목 케이스뿐만 아니라이 :

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

또는

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

^공백 의 시작 또는 뒤에 시작 [[:space:]]하고 알파벳 문자가 오는 정규식을 일치 [[:alpha:]]시킵니다. 전체적으로 (gsub의 g)는 이러한 모든 발생을 일치하는 시작 또는 공백 및 일치하는 알파벳 문자의 대문자 버전으로 바꿉니다 \\1\\U\\2. 이것은 펄 스타일 정규 표현식 일치로 수행해야합니다.

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

로 교체 인수에 대해 좀 더 구체적으로 gsub(), \\1'의 일부 사용 말한다 x즉, 부분 제 1 서브 표현 일치하는' x매칭 (^|[[:spacde:]]). 마찬가지로 두 번째 하위 표현식 \\2x일치하는 부분을 ​​사용한다고 말합니다 ([[:alpha:]]). \\U사용으로 설정 구문 perl=TRUE, 다음 문자를 대문자을하는 것을 의미한다. "우편 번호" \\1는 "우편 번호", \\2"코드", \\U\\2"코드", \\1\\U\\2"우편 번호"입니다.

?regexp페이지는 정규식을 이해하고 ?gsub일을 종합 하는 데 도움이 됩니다.


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"

대안 :

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

시험:

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

도움말 페이지에서 ?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"

The package BBmisc now contains the function 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!"

Alternative way with substring and regexpr:

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

You could also use the snakecase package:

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


This gives capital Letters to all major words

library(lettercase)
xString = str_title_case(xString)

참고URL : https://stackoverflow.com/questions/6364783/capitalize-the-first-letter-of-both-words-in-a-two-word-string

반응형