2022년 10월 26일 수요일

파이썬 textwrap (indent, 정렬, 줄바꿈)

 이 textwrap 모듈은 텍스트를 핸들링할때 indentation을 넣거나 빼거나, 글자수를 터미널 너비에 맞춘다거나 할때 유용합니다. 즉, pretty-print가 필요한 경우, 텍스트를 핸들링할때 유용합니다. 많은 텍스트 편집기 및 워드 프로세서에서 볼 수 있는 단락 줄 바꿈 또는 채우기 기능과 유사한 프로그래밍 기능을 제공합니다.

Filling Paragraphs

fill 함수에 대해 알아봅니다 fill() 함수는 텍스트를 width에 맞게 잘라주는 역할을 합니다.

# 실제 함수원형은 좀더 길지만, 아래 형태로 확인합니다
textwrap.fill(text: str, width: int) -> str 
import textwrap

text = '''
    I have two sisters who have made their careers in engineering. My first sister has
    a doctorate in civil engineering. She works in Australia designing mine tunnels for
    a raw materials company. My second sister earned a master's degree in electrical
    engineering. She works in the United States designing communication equipment.
    In summary, my two sisters both have graduate degrees in engineering and have
    careers in engineering.
'''

print (textwrap.fill(text,width=50))
'''
 I have two sisters who have made their careers in
engineering. My first sister has a doctorate in
civil engineering. She works in Australia
designing mine tunnels for a raw materials
company. My second sister earned a master's degree
in electrical engineering. She works in the United
States designing communication equipment. In
summary, my two sisters both have graduate degrees
in engineering and have careers in engineering.
'''

이제 텍스트가 왼쪽 정렬되지만 첫 번째 줄은 들여쓰기를 유지하고 각 후속 줄의 앞부터 공백이 단락에 포함됩니다.

textwrap 모듈은 예쁜 인쇄가 필요한 상황에서 출력할 텍스트의 형식을 지정하는 데 사용할 수 있습니다. 프로그래밍 방식을 제공합니다. 많은 텍스트 편집기에서 볼 수 있는 단락 줄 바꿈 또는 채우기 기능과 유사한 기능입니다.

Indentation 제거

이전 예제에는 출력에 포함된 탭과 추가 공백이 포함되어 있으므로 형식이 매우 명확하지 않습니다. 샘플 텍스트의 모든 줄에서 공통 공백 접두사를 제거하면 더 나은 결과를 얻을 수 있으며 코드 서식 자체를 제거하면서 Python 코드에서 직접 독스트링 또는 포함된 여러 줄 문자열을 사용할 수 있습니다. 샘플 문자열에는 이 기능을 설명하기 위해 도입된 인위적인 들여쓰기 수준이 있습니다. dedent를 사용하면 공백을 제거해 줍니다.

'''
I have two sisters who have made their careers in engineering. My first sister has
a doctorate in civil engineering. She works in Australia designing mine tunnels for
a raw materials company. My second sister earned a master's degree in electrical
engineering. She works in the United States designing communication equipment.
In summary, my two sisters both have graduate degrees in engineering and have
careers in engineering.
'''

아래 예제도 참고 합니다. indent가 들쭉날쭉 한 경우에도 이 공백을 댕겨줍니다. 다만, 실제 paragraph상의 indent를 제거하지 않습니다.

text2= '''
        I have two sisters who have made their careers in engineering. My first sister has
    a doctorate in civil engineering. She works in Australia designing mine tunnels for
    a raw materials company. My second sister earned a master's degree in electrical
    engineering. She works in the United States designing communication equipment.
        In summary, my two sisters both have graduate degrees in engineering and have
    careers in engineering.
'''

print (textwrap.dedent(text2))

'''
    I have two sisters who have made their careers in engineering. My first sister has
a doctorate in civil engineering. She works in Australia designing mine tunnels for
a raw materials company. My second sister earned a master's degree in electrical
engineering. She works in the United States designing communication equipment.
    In summary, my two sisters both have graduate degrees in engineering and have
careers in engineering.
'''

Dedent 와 Fill 함수 조합

다음은 dedent된 텍스트를 fill로 맞추어 봅니다. 위의 Text2 예제를 그대로 씁니다. dedent로 공백을 걷어내고, strip() 으로 좌우 여백을 완전히 잘라줍니다. 그리고 fill을 사용하면 width에 맞게 다시 text가 정렬이 됩니다.

text3= textwrap.dedent(text2).strip()
text4= textwrap.fill(text3,width=60)
print (text4)
'''
I have two sisters who have made their careers in
engineering. My first sister has a doctorate in civil
engineering. She works in Australia designing mine tunnels
for a raw materials company. My second sister earned a
master's degree in electrical engineering. She works in the
United States designing communication equipment.     In
summary, my two sisters both have graduate degrees in
engineering and have careers in engineering.
'''

Indents

때로는 문장 전체에 앞에 공백등을 넣어야 할때가 있습니다. 원래 문장에 4칸의 공백을 넣어봅니다.

text5='''
I have two sisters who have made their careers in
engineering. My first sister has a doctorate in civil
engineering. She works in Australia designing mine tunnels
for a raw materials company. My second sister earned a
master's degree in electrical engineering. She works in the
United States designing communication equipment.     In
summary, my two sisters both have graduate degrees in
engineering and have careers in engineering.
'''
print (textwrap.indent(text5,' '*4))

'''
    I have two sisters who have made their careers in
    engineering. My first sister has a doctorate in civil
    engineering. She works in Australia designing mine tunnels
    for a raw materials company. My second sister earned a
    master's degree in electrical engineering. She works in the
    United States designing communication equipment.     In
    summary, my two sisters both have graduate degrees in
    engineering and have careers in engineering.
'''

위와 같이 indent가 잘 삽입되었습니다.

이상으로 textwrap이 잘 동작 하는것을 확인해보았습니다. 이 textwrap은 종종 텍스트를 화면에 안잘리고 pretty-print하는 용도로 사용합니다.

댓글 없음:

댓글 쓰기