문제

반복되는 공간이없는 단일 라인 문자열로 멀티 라인 문자열을 축소하는 크로스 플랫폼 라이브러리 기능이 있습니까?

아래에서 약간의 저격을 느꼈지만, 아마도 C에서 최적화 된 표준 기능이 있는지 궁금합니다.

def collapse(input):
    import re
    rn = re.compile(r'(\r\n)+')
    r = re.compile(r'\r+')
    n = re.compile(r'\n+')
    s = re.compile(r'\ +')
    return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input))))

추신 : 좋은 관찰에 감사드립니다. ' '.join(input.split()) 제 경우에 실제로 두 번 더 빨리 실행되므로 승자 인 것 같습니다. r'\s+' 성과선.

도움이 되었습니까?

해결책

내장 string.split() 메소드는 공백 실행에서 분할되므로이를 사용한 다음 다음과 같은 공간을 사용하여 결과 목록에 합류 할 수 있습니다.

' '.join(my_string.split())

다음은 완전한 테스트 스크립트입니다.

TEST = """This
is        a test\twith a
  mix of\ttabs,     newlines and repeating
whitespace"""

print ' '.join(TEST.split())
# Prints:
# This is a test with a mix of tabs, newlines and repeating whitespace

다른 팁

당신은 올바른 아이디어를 가지고있었습니다. Python 매뉴얼을 좀 더 자세히 읽어야했습니다.

import re
somewhitespace = re.compile(r'\s+')
TEST = """This
is        a test\twith a
  mix of\ttabs,     newlines and repeating
whitespace"""

somewhitespace.sub(' ', TEST)

'This is a test with a mix of tabs, newlines and repeating whitespace'
multi_line.replace('\n', '')

일을 할 것입니다. '\n' 파이썬에서 보편적 인 라인 문자입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top