Programing

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

lottogame 2020. 7. 2. 07:47
반응형

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


그렇게 " 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_allstr_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앞뒤 공백 만 제거 하는 기능이 있습니다.

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_charclassstri_trim

stringi플랫폼 독립적 인 ICU 라이브러리를 기반으로 하며 광범위한 문자열 조작 기능을 갖추고 있습니다. 등가물 위의은 다음과 같습니다 :

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

여기서 "\\p{WHITE_SPACE}"등가 공백 인 것으로 간주 유니 코드 코드 포인트들의 세트에 대한 대체 구문 "[[:space:]]", "\\s"space(). 보다 복잡한 정규식 대체에는 stri_replace_all_regex.

stringi also has trim functions.

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

I just learned about the "stringr" package to remove white space from the beginning and end of a string with str_trim( , side="both") but it also has a replacement function so that:

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

[1] "xxyy112233"

Please note that soultions written above removes only space. If you want also to remove tab or new line use stri_replace_all_charclass from stringi package.

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

Use [[:blank:]] to match any kind of horizontal white_space characters.

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

x = "xx yy 11 22 33"

gsub(" ", "", x)

> [1] "xxyy112233"

The function str_squish() from package stringr of tidyverse does the magic!

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

This way you can remove all spaces from all character variables in your data frame. If you would prefer to choose only some of the variables, use mutateor mutate_at.

library(dplyr)
library(stringr)

remove_all_ws<- function(string){
    return(gsub(" ", "", str_squish(string)))
}

df<-df %>%  mutate_if(is.character, remove_all_ws)


From stringr library you could try this:

  1. Remove consecutive fill blanks
  2. Remove fill blank

    library(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

반응형