鍍金池/ 教程/ Python/ 重新格式化段落
文本翻譯
提取URL地址
處理PDF
塊分類
搜索和匹配
大寫轉(zhuǎn)換
提取電子郵件地址
字符串的不變性
文本處理狀態(tài)機
雙字母組
閱讀RSS提要
單詞替換
WordNet接口
重新格式化段落
標記單詞
向后讀取文件
塊和裂口
美化打印數(shù)字
拼寫檢查
將二進制轉(zhuǎn)換為ASCII
文本分類
文字換行
頻率分布
字符串作為文件
約束搜索
詞干算法
符號化
同義詞和反義詞
過濾重復的字詞
刪除停用詞
Python文本處理教程
文字摘要
段落計數(shù)令牌
語料訪問
文字改寫
文本處理簡介
處理Word文檔
Python文本處理開發(fā)環(huán)境
排序行

重新格式化段落

當我們處理大量文本并將其呈現(xiàn)為可呈現(xiàn)的格式時,需要格式化段落??赡苤幌氪蛴【哂刑囟▽挾鹊拿恳恍?,或者在打印詩詞時增加每一行的縮進。 在本章中,將使用textwrap3模塊根據(jù)需要格式化段落。

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

pip install textwrap3

環(huán)繞固定寬度

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

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?

下一篇:文字改寫