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

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

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

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

โดย jirawoot » 04/11/2019 2:57 pm

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/

ข้างบน