Python – Reformatting a paragraph

Python – Reformatting Paragraphs

When processing large amounts of text and presenting them in a visually appealing format, we need to format our paragraphs. We might want to print only lines of a specific width, or perhaps increase the indentation of each line when printing poetry. In this chapter, we use a module called textwrap3 to format paragraphs as needed.

First, we need to install the required packages as shown below.

pip install textwrap3

Fixed-Width Wrappers

In this example, we specify a width of 30 characters for each line in the paragraph. We use the wrap function by specifying a value for the width parameter.

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])

When we run the above program, we get the following output

In late summer 1945, guests
are gathered for the Wedding
reception of Don Vito
Corleone's 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.

Variable Indentation

In this example, we increase the indentation of each line of the poem to be printed by one unit.

import textwrap3

FileName = ("pathpoem.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

When we run the above program, we get the following output

**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?

Leave a Reply

Your email address will not be published. Required fields are marked *