Python reformatting paragraphs

Reformatting Paragraphs in Python

When processing large amounts of text and presenting them in an acceptable format, we need to format the paragraphs. We might want to print each line at a specific width, or add indents to 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 by following the steps below.

pip install textwrap3

Fixed-Width Line Wrapping

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

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 running the above program, we will 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 poetry to be printed.

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 *