重新格式化段落

當我們處理大量文本並將其呈現爲可呈現的格式時,需要格式化段落。可能只想打印具有特定寬度的每一行,或者在打印詩詞時增加每一行的縮進。 在本章中,將使用textwrap3模塊根據需要格式化段落。

首先,需要安裝所需的包,如下所示 -

pip install textwrap3

環繞固定寬度

在此示例中,爲段落的每一行指定了30個字符的寬度。通過爲width參數指定值來使用wrap函數。

from textwrap3 import wrap

text = 'In late summer 1945, guests are gathered for the wedding reception of Don Vito Corleones daughter Connie (Talia Shire) and Carlo Rizzi (Gianni Russo). Vito (Marlon Brando), the head of the Corleone Mafia family, is known to friends and associates as Godfather. He and Tom Hagen (Robert Duvall), the Corleone family lawyer, are hearing requests for favors because, according to Italian tradition, no Sicilian can refuse a request on his daughters wedding day.'

x = wrap(text, 30)
for i in range(len(x)):
    print(x[i])

當運行上面的程序時,我們得到以下輸出 -

In late summer 1945, guests
are gathered for the wedding
reception of Don Vito
Corleones daughter Connie
(Talia Shire) and Carlo Rizzi
(Gianni Russo). Vito (Marlon
Brando), the head of the
Corleone Mafia family, is
known to friends and
associates as Godfather. He
and Tom Hagen (Robert Duvall),
the Corleone family lawyer,
are hearing requests for
favors because, according to
Italian tradition, no Sicilian
can refuse a request on his
daughters wedding day.

變量縮進

在這個例子中,增加了要打印詩語的每一行的縮進。

import textwrap3

FileName = ("path\poem.txt")

print("**Before Formatting**")
print(" ")

data=file(FileName).readlines()
for i in range(len(data)):
   print data[i]

print(" ")
print("**After Formatting**")
print(" ")
data=file(FileName).readlines()
for i in range(len(data)):
    dedented_text = textwrap3.dedent(data[i]).strip()
    print dedented_text

當運行上面的程序時,得到以下輸出 -

**Before Formatting**

 Summer is here.
  Sky is bright.
    Birds are gone.
     Nests are empty.
      Where is Rain?

**After Formatting**

Summer is here.
Sky is bright.
Birds are gone.
Nests are empty.
Where is Rain?