it-source

문자열에서 모든 공백을 제거하는 방법은 무엇입니까?

criticalcode 2023. 7. 15. 10:15
반응형

문자열에서 모든 공백을 제거하는 방법은 무엇입니까?

그렇게" xx yy 11 22 33 "될 것입니다"xxyy112233"어떻게 하면 이를 달성할 수 있을까요?

일반적으로 우리는 벡터화된 솔루션을 원하기 때문에 다음은 더 나은 테스트 예제입니다.

whitespace <- " \t\n\r\v\f" # space, tab, newline, 
                            # carriage return, vertical tab, form feed
x <- c(
  " x y ",           # spaces before, after and in between
  " \u2190 \u2192 ", # contains unicode chars
  paste0(            # varied whitespace     
    whitespace, 
    "x", 
    whitespace, 
    "y", 
    whitespace, 
    collapse = ""
  ),   
  NA                 # missing
)
## [1] " x y "                           
## [2] " ← → "                           
## [3] " \t\n\r\v\fx \t\n\r\v\fy \t\n\r\v\f"
## [4] NA

기본 R 접근법:gsub

gsub 문자열의 모든 인스턴스를 바꿉니다(fixed = TRUE) 또는 정규식(fixed = FALSE(기본값)을 입력합니다.모든 공백을 제거하려면 다음을 사용합니다.

gsub(" ", "", x, fixed = TRUE)
## [1] "xy"                            "←→"             
## [3] "\t\n\r\v\fx\t\n\r\v\fy\t\n\r\v\f" NA 

DWin이 언급했듯이, 이 경우.fixed = TRUE고정 문자열을 일치시키는 것이 정규식을 일치시키는 것보다 빠르기 때문에 필요하지는 않지만 약간 더 나은 성능을 제공합니다.

모든 유형의 공백을 제거하려면 다음을 사용합니다.

gsub("[[:space:]]", "", x) # note the double square brackets
## [1] "xy" "←→" "xy" NA 

gsub("\\s", "", x)         # same; note the double backslash

library(regex)
gsub(space(), "", x)       # same

"[:space:]" 는 모든 공백 문자와 일치하는 R 전용 정규식 그룹입니다. \s같은 일을 하는 언어 독립적인 정규 표현식입니다.


stringr접근:str_replace_all그리고.str_trim

stringr기본 R 함수 주변에 더 많은 사람이 읽을 수 있는 래퍼를 제공합니다(2014년 12월 현재 개발 버전에는 위에 구축된 분기가 있습니다).stringi아래에 언급됨).[]를 사용한 위 명령어의 등가물str_replace_all][3]다음과 같습니다.

library(stringr)
str_replace_all(x, fixed(" "), "")
str_replace_all(x, space(), "")

stringr선행 및 후행 공백만 제거하는 기능도 있습니다.

str_trim(x) 
## [1] "x y"          "← →"          "x \t\n\r\v\fy" NA    
str_trim(x, "left")    
## [1] "x y "                   "← → "    
## [3] "x \t\n\r\v\fy \t\n\r\v\f" NA     
str_trim(x, "right")    
## [1] " x y"                   " ← →"    
## [3] " \t\n\r\v\fx \t\n\r\v\fy" NA      

stringi접근:stri_replace_all_charclass그리고.stri_trim

stringi플랫폼에 독립적인 ICU 라이브러리를 기반으로 하며 광범위한 문자열 조작 기능이 있습니다.위의 내용은 다음과 같습니다.

library(stringi)
stri_replace_all_fixed(x, " ", "")
stri_replace_all_charclass(x, "\\p{WHITE_SPACE}", "")

다음은 빈 공간으로 간주되는 유니코드 코드 포인트 집합에 대한 대체 구문입니다."[[:space:]]","\\s"그리고.space()보다 복잡한 정규 표현식 대체의 경우 다음과 같은 것들이 있습니다.stri_replace_all_regex.

stringi트림 기능도 있습니다.

stri_trim(x)
stri_trim_both(x)    # same
stri_trim(x, "left")
stri_trim_left(x)    # same
stri_trim(x, "right")  
stri_trim_right(x)   # same

str_syslog(, side="both")가 있는 문자열의 시작과 끝에서 공백을 제거하는 "stringr" 패키지에 대해 방금 배웠지만, 다음과 같은 대체 기능도 있습니다.

a <- " xx yy 11 22 33 " 
str_replace_all(string=a, pattern=" ", repl="")

[1] "xxyy112233"
x = "xx yy 11 22 33"

gsub(" ", "", x)

> [1] "xxyy112233"

사용하다[[:blank:]]모든 종류의 수평 white_space 문자와 일치합니다.

gsub("[[:blank:]]", "", " xx yy 11 22  33 ")
# [1] "xxyy112233"

위에 쓴 영혼은 공간만 제거한다는 점에 유의하십시오.탭이나 새 줄도 제거하려면stri_replace_all_charclass부터stringi꾸러미

library(stringi)
stri_replace_all_charclass("   ala \t  ma \n kota  ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"

함수str_squish()포장에서.stringr정갈한 verse가 마법을 부립니다!

library(dplyr)
library(stringr)

df <- data.frame(a = c("  aZe  aze s", "wxc  s     aze   "), 
                 b = c("  12    12 ", "34e e4  "), 
                 stringsAsFactors = FALSE)
df <- df %>%
  rowwise() %>%
  mutate_all(funs(str_squish(.))) %>%
  ungroup()
df

# A tibble: 2 x 2
  a         b     
  <chr>     <chr> 
1 aZe aze s 12 12 
2 wxc s aze 34e e4

다른 접근 방식을 고려할 수 있습니다.

library(stringr)
str_replace_all(" xx yy 11 22  33 ", regex("\\s*"), "")

#[1] "xxyy112233"

\\s: 공백, 탭, 세로 탭, 새 줄, 양식 피드, 캐리지 리턴 일치

0회 이상 일치

income<-c("$98,000.00 ", "$90,000.00 ", "$18,000.00 ", "")

다음 시간 이후에 공간을 제거하려면.00을 사용합니다.trimws()기능.

income<-trimws(income)

stringr 라이브러리에서 다음을 시도할 수 있습니다.

  1. 연속된 채우기 빈칸 제거
  2. 채우기 공백 제거

    라이브러리(stringr)

                2.         1.
                |          |
                V          V
    
        str_replace_all(str_trim(" xx yy 11 22  33 "), " ", "")
    

언급URL : https://stackoverflow.com/questions/5992082/how-to-remove-all-whitespace-from-a-string

반응형