Python文本处理

重新格式化段落

重新格式化段落详细操作教程
当我们处理大量文本并将其呈现为可呈现的格式时,需要格式化段落。可能只想打印具有特定宽度的每一行,或者在打印诗词时增加每一行的缩进。 在本章中,将使用textwrap3模块根据需要格式化段落。
首先,需要安装所需的包,如下所示 -
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
pip install textwrap3

环绕固定宽度

在此示例中,为段落的每一行指定了30个字符的宽度。通过为width参数指定值来使用wrap函数。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
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])
当运行上面的程序时,我们得到以下输出 -
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
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.
变量缩进
在这个例子中,增加了要打印诗语的每一行的缩进。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
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
当运行上面的程序时,得到以下输出 -
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
**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?
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4