Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Text Wrapping และ Filling ใน Python (โมดูล textwrap)

โมดูล textwrap จัดรูปแบบข้อความ: Wrap, Fill, Shorten, Indent ให้พอดีกับ Width ที่กำหนด

import textwrap


TextWrapper Attributes (Constructor Parameters)

AttributeDefaultคำอธิบาย
width70Max Line Width
expand_tabsTrueExpand Tabs เป็น Spaces
tabsize8Tab Size
replace_whitespaceTrueReplace Whitespace Chars ด้วย Space
drop_whitespaceTrueDrop Whitespace ที่ ראש/ท้ายบรรทัด
initial_indent''Prefix บรรทัดแรก
subsequent_indent''Prefix บรรทัดต่อไป
placeholder'[...]'Suffix เมื่อ Truncate
max_linesNoneMax Lines (None = Unlimited)
break_long_wordsTrueBreak Long Words
break_on_hyphensTrueBreak at Hyphens

Convenience Functions

textwrap.wrap(text, width=70, **kwargs)

คืน List ของ Lines ที่ Wrapped แล้ว

textwrap.fill(text, width=70, **kwargs)

คืน Single String (Joined with Newlines)

textwrap.shorten(text, width, **kwargs)

Truncate Text ให้พอดี Width + Placeholder

textwrap.dedent(text)

ลบ Common Leading Whitespace (สำหรับ Multi-line Strings)

textwrap.indent(text, prefix, predicate=None)

เพิ่ม Prefix ทุกบรรทัด (Predicate ควบคุมบรรทัดไหน)


โค้ดตัวอย่าง

import textwrap

text = """Python is a general-purpose interpreted, interactive, object-oriented, 
and high-level programming language. It was created by Guido van Rossum 
during 1985-1990. Like Perl, Python source code is also available under 
the GNU General Public License (GPL)."""

# 1. Wrap -> List
wrapper = textwrap.TextWrapper(width=40)
lines = wrapper.wrap(text)
for i, line in enumerate(lines):
    print(f"{i}: {line}")

# 2. Fill -> String
print("\n--- Fill ---")
print(wrapper.fill(text))

# 3. Shorten
print("\n--- Shorten (150 chars) ---")
short = textwrap.shorten(text, width=150, placeholder='...')
print(wrapper.fill(short))

# 4. Dedent
code = """
    def hello():
        print("Hello")
        if True:
            print("World")
"""
print("\n--- Dedent ---")
print(textwrap.dedent(code))

# 5. Indent
print("\n--- Indent ---")
print(textwrap.indent(textwrap.dedent(code), '>>> '))

# 6. Custom Indents
wrapper2 = textwrap.TextWrapper(
    width=50,
    initial_indent='* ',
    subsequent_indent='  '
)
print("\n--- Custom Indent ---")
print(wrapper2.fill(text))

ผลลัพธ์

0: Python is a general-purpose interpreted,
1: interactive, object-oriented, and high-
2: level programming language. It was
3: created by Guido van Rossum during
4: 1985-1990. Like Perl, Python source
5: code is also available under the
6: GNU General Public License (GPL).

--- Fill ---
Python is a general-purpose interpreted,
interactive, object-oriented, and high-
level programming language. It was
created by Guido van Rossum during
1985-1990. Like Perl, Python source
code is also available under the
GNU General Public License (GPL).

--- Shorten (150 chars) ---
Python is a general-purpose interpreted,
interactive, object-oriented, and high-
level programming language. It was created
by Guido van Rossum [...]

--- Dedent ---
def hello():
    print("Hello")
    if True:
        print("World")

--- Indent ---
>>> def hello():
>>>     print("Hello")
>>>     if True:
>>>         print("World")

--- Custom Indent ---
* Python is a general-purpose interpreted,
  interactive, object-oriented, and high-
  level programming language. It was
  created by Guido van Rossum during
  1985-1990. Like Perl, Python source
  code is also available under the
  GNU General Public License (GPL).

การประยุกต์ใช้จริง

  • CLI Help Text Formatting
  • Log Message Formatting
  • Email/Report Generation
  • Code Generation (Indentation)
  • Terminal UI Text Layout
  • Docstring Cleanup (inspect.cleandoc ใช้ dedent ภายใน)

Advanced: Custom Word Breaking

class NoBreakWrapper(textwrap.TextWrapper):
    def break_long_words(self, word, space_left):
        # ไม่ Break คำยาว -> ให้ Overrun Width
        return False

wrapper = NoBreakWrapper(width=20)
print(wrapper.fill("Supercalifragilisticexpialidocious"))
# Supercalifragilisticexpialidocious (เกิน Width)