programing

공백은 어떻게 잘라요?

goodjava 2022. 11. 20. 11:12

공백은 어떻게 잘라요?

문자열에서 공백(스페이스와 탭)을 잘라내는 Python 기능이 있습니까?

지정된 입력은 " " " 입니다." \t example string\t " becomes가 되다"example string".

양쪽에 공백이 있는 경우 다음을 사용합니다.

s = "  \t a string example\t  "
s = s.strip()

오른쪽 공백의 경우 다음을 사용합니다.

s = s.rstrip()

왼쪽에 공백이 있는 경우 다음을 사용합니다.

s = s.lstrip()

다음과 같은 임의의 함수에 임의의 문자를 삭제하는 인수를 지정할 수 있습니다.

s = s.strip(' \t\n\r')

.\t,\n , 「」\r문자열 양쪽에 있는 문자

위의 예에서는 문자열의 왼쪽과 오른쪽에서만 문자열을 삭제합니다.문자열 중간에서 문자도 삭제할 경우 다음을 수행합니다.

import re
print(re.sub('[\s+]', '', s))

다음과 같이 출력됩니다.

astringexample

Python에서는 trim 메서드가 지정됩니다.strip:

str.strip()  # trim
str.lstrip()  # left trim
str.rstrip()  # right trim

선행 및 후행 공백의 경우:

s = '   foo    \t   '
print s.strip() # prints "foo"

그렇지 않으면 정규 표현은 다음과 같이 동작합니다.

import re
pat = re.compile(r'\s+')
s = '  \t  foo   \t   bar \t  '
print pat.sub('', s) # prints "foobar"

또한 매우 단순하고 기본적인 함수 str.replace()를 사용할 수도 있습니다.이 기능은 공백 및 탭과 함께 사용할 수 있습니다.

>>> whitespaces = "   abcd ef gh ijkl       "
>>> tabs = "        abcde       fgh        ijkl"

>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl

심플하고 간단합니다.

#how to trim a multi line string or a file

s=""" line one
\tline two\t
line three """

#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.

s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']

print [i.strip() for i in s1]
['line one', 'line two', 'line three']




#more details:

#we could also have used a forloop from the begining:
for line in s.splitlines():
    line=line.strip()
    process(line)

#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
    line=line.strip()
    process(line)

#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']

아직 아무도 이 정규식 솔루션을 게시하지 않았습니다.

일치:

>>> import re
>>> p=re.compile('\\s*(.*\\S)?\\s*')

>>> m=p.match('  \t blah ')
>>> m.group(1)
'blah'

>>> m=p.match('  \tbl ah  \t ')
>>> m.group(1)
'bl ah'

>>> m=p.match('  \t  ')
>>> print m.group(1)
None

검색('공백만' 입력 대소문자를 다르게 처리해야 함):

>>> p1=re.compile('\\S.*\\S')

>>> m=p1.search('  \tblah  \t ')
>>> m.group()
'blah'

>>> m=p1.search('  \tbl ah  \t ')
>>> m.group()
'bl ah'

>>> m=p1.search('  \t  ')
>>> m.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

「 」를 사용하고 re.sub 이 있는 할 수 않을 수 이는 바람직하지 않을 수 있습니다.

공백에는 공간, CRLF가 포함됩니다.그래서 우리가 사용할 수 있는 우아한 원라이너 스트링 기능은 번역입니다.

' hello apple'.translate(None, ' \n\t\r')

아니면 철저하게 하고 싶다면

import string
' hello  apple'.translate(None, string.whitespace)

(re.subbacks +', ', (my_str.replace\n', ')'), strip().

불필요한 공백과 줄 바꿈 문자가 모두 삭제됩니다.도움이 되었으면 좋겠다

import re
my_str = '   a     b \n c   '
formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()

그 결과 다음과 같이 됩니다.

a b \n c 로 변경됩니다. 'a b c'

    something = "\t  please_     \t remove_  all_    \n\n\n\nwhitespaces\n\t  "

    something = "".join(something.split())

출력:

삭제_모든_스페이스


Adding Le Droid's comment to the answer. To separate with a space:

    something = "\t  please     \t remove  all   extra \n\n\n\nwhitespaces\n\t  "
    something = " ".join(something.split())

출력:

여분의 공백을 모두 제거해 주세요.

여러 가지 이해도를 가지고 여러 가지 해결책을 살펴본 결과, 줄이 쉼표로 분리되면 어떻게 해야 하나 하는 생각이 들었습니다.

문제

연락처 정보의 csv를 처리하려고 할 때, 이 문제의 해결 방법이 필요했습니다.외부 공백과 정크 사이즈는 잘라내지만, 후행 콤마와 내부 공백은 유지합니다.연락처에 메모가 있는 필드를 사용하여 좋은 것을 남겨두고 쓰레기를 치우고 싶었습니다.구두점과 왕겨를 모두 제거하고, 나중에 다시 만들고 싶지 않기 때문에 복합 토큰 사이의 공백을 잃고 싶지 않았습니다.

및 "" " " " " "[\s_]+?\W+

이 ')의 단일 한 수)까지 느릿느릿 .이 경우, 「」('_')는 「1 ~」( 「」)입니다.[\s_]+? 앞에 문자는 다음과 같습니다. 1 ~ 무무 、 무무 、 무 that 、 음 that 、 음 that that that 。\W+는 (에 합니다.[^a-zA-Z0-9_]구체적으로는 공백(늘 문자(\0), 탭(\t), 줄바꿈(\n), 피드포워드(\f), 캐리지 리턴(\r))을 찾습니다.

이 방법의 장점은 두 가지입니다.

  1. 함께 보관하고 싶은 완전한 단어/단어 사이의 공백을 제거하지 않는다.

  2. Python의 메서드 Python은 Python을 합니다.strip() 끝만 는 늘 예:줄의 되어 있습니다.또, 「 」는 「 arg」의 「 」( 「 」)를 참조해 주세요).strip()regex 패턴이 삭제되는 동안 모두 삭제되는 것은 아닙니다). text.strip(' \n\t\r')

이것은 OP의 질문을 넘어서는 것이지만, 텍스트 데이터 내에 이상한 병리학적 인스턴스가 있는 경우가 많다고 생각합니다(일부 텍스트에서는 이스케이프 문자가 어떻게 되었는지).게다가 리스트와 같은 문자열에서는, 딜리미터가 2개의 공백 문자 또는 「-」나 「-」와 같이, 단어가 아닌 문자를 구분하지 않는 한 딜리미터를 삭제하지 않습니다.

NB: CSV 자체의 딜리미터에 대해서는 언급하지 않습니다.데이터가 목록과 같은 CSV 내의 인스턴스(서브스트링의 c.s. 문자열)만 해당됩니다.

완전 공개:제가 문자를 조작한 지 한 달 정도밖에 안 돼서 지난 2주 동안만 정규식을 했어요 그래서 제가 놓치고 있는 뉘앙스가 분명 있어요즉, 작은 문자열 모음(내 문자열은 12,000 행과 40 개의 홀수 열의 데이터 프레임에 있음)의 경우, 관련 없는 문자를 삭제하기 위한 패스 후 마지막 단계로서, 특히 단어 이외의 문자에 의해 결합되는 텍스트를 구분하고 싶지만 whi를 추가하지 않는 경우에 매우 효과적입니다.tespace는 예전엔 없던 곳이에요.

예:

import re


text = "\"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, jim.somedude@blahblah.com, ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, , , , \r, , \0, ff dd \n invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, \n i69rpofhfsp9t7c practice 20ignition - 20june \t\n .2134.pdf 2109                                                 \n\n\n\nklkjsdf\""

print(f"Here is the text as formatted:\n{text}\n")
print()
print("Trimming both the whitespaces and the non-word characters that follow them.")
print()
trim_ws_punctn = re.compile(r'[\s_]+?\W+')
clean_text = trim_ws_punctn.sub(' ', text)
print(clean_text)
print()
print("what about 'strip()'?")
print(f"Here is the text, formatted as is:\n{text}\n")
clean_text = text.strip(' \n\t\r')  # strip out whitespace?
print()
print(f"Here is the text, formatted as is:\n{clean_text}\n")

print()
print("Are 'text' and 'clean_text' unchanged?")
print(clean_text == text)

출력은 다음과 같습니다.

Here is the text as formatted:

"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, jim.somedude@blahblah.com, ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf" 

using regex to trim both the whitespaces and the non-word characters that follow them.

"portfolio, derp, hello-world, hello-, world, founders, mentors, ffib, biff, 1, 12.18.02, 12, 2013, 9874890288, ff, series a, exit, general mailing, fr, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk,  jim.somedude@blahblah.com, dd invites,subscribed,, master, dd invites,subscribed, ff dd invites, subscribed, alumni spring 2012 deck: https: www.dropbox.com s, i69rpofhfsp9t7c practice 20ignition 20june 2134.pdf 2109 klkjsdf"

Very nice.
What about 'strip()'?

Here is the text, formatted as is:

"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, jim.somedude@blahblah.com, ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf"


Here is the text, after stipping with 'strip':


"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, jim.somedude@blahblah.com, ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf"
Are 'text' and 'clean_text' unchanged? 'True'

따라서 스트립은 한 번에 하나의 공백을 제거합니다. 「」는 「」입니다.strip()괜찮습니다. 하지만 상황이 더 복잡해지면 regex와 유사한 패턴이 더 일반적인 설정에 도움이 될 수 있습니다.

그것을 실제로 보다.

Python 3을 사용하는 경우: 인쇄 명세서에서 sep=seclar로 끝납니다.그러면 모든 공간이 분리됩니다.

예:

txt="potatoes"
print("I love ",txt,"",sep="")

인쇄:감자를 좋아해요.

대신: 나는 감자를 사랑한다.

당신의 경우 \t를 타려고 할 테니 sep="\t"를 실행하세요.

번역해 보다

>>> import string
>>> print '\t\r\n  hello \r\n world \t\r\n'

  hello 
 world  
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr)
'     hello    world    '
>>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'

문자열의 처음과 끝에만 공백을 잘라내려면 다음과 같이 하십시오.

some_string = "    Hello,    world!\n    "
new_string = some_string.strip()
# new_string is now "Hello,    world!"

이는 QT의 QString::trimed() 메서드와 매우 유사하며 내부 공백은 그대로 두고 선행 및 후행 공백을 제거합니다.

그러나 선행 및 후행 공백을 제거할 뿐만 아니라 연속된 모든 내부 공백을 하나의 공백 문자로 "스퀴징"하는 QT의 QString::simplified() 메서드와 같은 방법을 원하는 경우 다음 조합을 사용할 수 있습니다..split()그리고." ".join, 다음과 같이 합니다.

some_string = "\t    Hello,  \n\t  world!\n    "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"

이 마지막 예에서는 문자열의 시작과 끝에 있는 공백을 잘라내면서 내부 공백의 각 시퀀스가 단일 공백으로 대체되었습니다.

일반적으로 다음과 같은 방법을 사용하고 있습니다.

>>> myStr = "Hi\n Stack Over \r flow!"
>>> charList = [u"\u005Cn",u"\u005Cr",u"\u005Ct"]
>>> import re
>>> for i in charList:
        myStr = re.sub(i, r"", myStr)

>>> myStr
'Hi Stack Over  flow'

메모: 이는 "\n", "\r" 및 "\t"를 삭제하는 경우에만 해당됩니다.여분의 공간은 삭제되지 않습니다.

이렇게 하면 문자열의 시작과 끝 모두에서 공백과 줄바꿈이 모두 제거됩니다.

>>> s = "  \n\t  \n   some \n text \n     "
>>> re.sub("^\s+|\s+$", "", s)
>>> "some \n text"

언급URL : https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace