Python 重新格式化段落

Python 重新格式化段落

当我们处理大量文本并将其呈现为可接受的格式时,需要对段落进行格式化。我们可能只想以特定宽度打印每一行,或者在打印诗歌时为每一行增加缩进。在本章中,我们使用一个名为 textwrap3 的模块来根据需要格式化段落。

首先,我们需要按照以下步骤安装所需的软件包。

pip install textwrap3

固定宽度换行

在这个示例中,我们为一个段落的每一行指定了30个字符的宽度。通过指定宽度参数来使用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?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程