วิธีการใช้ textwarp เพื่อทำการนำข้อความที่ยาวเกินไปมาขึ้นบรรทัดใหม่

แชร์ความรู้ภาษา Python ไพทอน การเขียนโปรแกรมภาษาไพทอน

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
jirawoot
PHP VIP Members
PHP VIP Members
โพสต์: 3129
ลงทะเบียนเมื่อ: 17/06/2019 10:30 am

วิธีการใช้ textwarp เพื่อทำการนำข้อความที่ยาวเกินไปมาขึ้นบรรทัดใหม่

โพสต์ที่ยังไม่ได้อ่าน โดย jirawoot »

textwarp คือ โมดูลที่ใช้สำหรับอำนวยความสะดวกเกี่ยวกับข้อความ สามารถใช้ให้ทำการขึ้นบรรทัดใหม่ได้ ซึ่งจะเป็นโมดุลที่ใช้ในงานใน Python โดยการใช้นั้นจะต้องทำเรียกใช้หรือ import เข้ามาใช้ตัวของ textwarp จะมีฟังก์ชั่นอยู่ 3 ตัว คือ wrap() จะใช้สำหรับการย่อหน้าและการเข้าบรรทัดใหม่ ส่วนของ fill() ความสามารถจะคล้ายกับตัวของ wrap ตัวฟังก์ชั่น dedent() จะใช้สำหรับการลบช่องว่างที่นำหน้าออกจากทุกบรรทัดในของข้อความ โดยทั้ง 3 อย่างนี้มีตัวอย่างประกอบดังนี้

ฟังก์ชั่น wrap(text, width=70, **kwargs)

โค้ด: เลือกทั้งหมด

import textwrap

text = 'This function wraps the input paragraph such that each line in the paragraph is at most width characters long. ' \
        'The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content'

wrapper = textwrap.TextWrapper(width=50)
word_list = wrapper.wrap(text=text)

for element in word_list:
    print(element)
Output

โค้ด: เลือกทั้งหมด

This function wraps the input paragraph such that
each line in the paragraph is at most width
characters long. The wrap method returns a list of
output lines. The returned list is empty if the
wrapped output has no content
ฟังก์ชั่น fill(text, width=70, **kwargs)

โค้ด: เลือกทั้งหมด

import textwrap

value = """This function returns the answer as STRING and not LIST."""
wrapper = textwrap.TextWrapper(width=50)

string = wrapper.fill(text=value)

print (string)
Output

โค้ด: เลือกทั้งหมด

This function returns the answer as STRING and not
LIST.
ฟังก์ชั่น dedent(text)

โค้ด: เลือกทั้งหมด

import textwrap
wrapper = textwrap.TextWrapper(width=50)
s = '''\ 
    hello 
      world 
    '''
print(repr(s))
text = textwrap.dedent(s)
print(repr(text))
Output

โค้ด: เลือกทั้งหมด

'\\ \n    hello \n      world \n    '
'\\ \n    hello \n      world \n'


อ้างอิง
https://docs.python.org/2/library/textwrap.html
https://www.geeksforgeeks.org/textwrap-text-wrapping-filling-python/
https://pymotw.com/3/textwrap/
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 109