All Courses

Python - Text wrapping

Robin Marshel

2 years ago

Text Wrapping in Python | Insideaiml
Table of Content
  • Text Wrapping Methods
  • Example Code
  • Output
            Text wrapping is required when the text grabbed from some source is not properly formatted to be displayed within the available screen width. This is achieved by using the below package which can be installed in our environment with below command.
pip install parawrap
The beneath section has a solitary string of text which is ceaseless. on applying for the wrap work we can perceive how the content is isolated into different lines isolated with commas.

import parawrap

text = "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 daughter's wedding day. One of the men who asks the Don for a favor is Amerigo Bonasera, a successful mortician and acquaintance of the Don, whose daughter was brutally beaten by two young men because she refused their advances; the men received minimal punishment from the presiding judge. The Don is disappointed in Bonasera, who'd avoided most contact with the Don due to Corleone's nefarious business dealings. The Don's wife is godmother to Bonasera's shamed daughter, a relationship the Don uses to extract new loyalty from the undertaker. The Don agrees to have his men punish the young men responsible (in a non-lethal manner) in return for future service if necessary."

print(parawrap.wrap(text))
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 daughter's wedding day. One of", 'the men who asks the Don for a favor is Amerigo Bonasera, a successful', 'mortician and acquaintance of the Don, whose daughter was brutally', 'beaten by two young men because she refused their advances; the men', 'received minimal punishment from the presiding judge. The Don is', "disappointed in Bonasera, who'd avoided most contact with the Don due", "to Corleone's nefarious business dealings. The Don's wife is godmother", "to Bonasera's shamed daughter, a relationship the Don uses to extract", 'new loyalty from the undertaker. The Don agrees to have his men punish', 'the young men responsible (in a non-lethal manner) in return for', 'future service if necessary.']
We can likewise apply for the wrap work with explicit width as info boundary which will slice the words whenever required to keep up the necessary width of the wrap work.

import parawrap

text = "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 daughter's wedding day. One of the men who asks the Don for a favor is Amerigo Bonasera, a successful mortician and acquaintance of the Don, whose daughter was brutally beaten by two young men because she refused their advances; the men received minimal punishment from the presiding judge. The Don is disappointed in Bonasera, who'd avoided most contact with the Don due to Corleone's nefarious business dealings. The Don's wife is godmother to Bonasera's shamed daughter, a relationship the Don uses to extract new loyalty from the undertaker. The Don agrees to have his men punish the young men responsible (in a non-lethal manner) in return for future service if necessary."

print(parawrap.wrap(text,5))

At the point when we run the above program, we get the accompanying yield −

['In', 'late ', 'summe', 'r', '1945,', 'guest', 's are', 'gathe', 'red', 'for', 'the w', 'eddin', 'g rec', 'eptio', 'n of', 'Don', 'Vito ', 'Corle', "one's", 'daugh', 'ter C', 'onnie', '(Tali', 'a Shi', 're)', 'and', 'Carlo', 'Rizzi', '(Gian', 'ni Ru', 'sso).', 'Vito ', '(Marl', 'on Br', 'ando)', ', the', 'head', 'of', 'the C', 'orleo', 'ne', 'Mafia', 'famil', 'y, is', 'known', 'to fr', 'iends', 'and a', 'ssoci', 'ates', 'as Go', 'dfath', 'er.', 'He', 'and', 'Tom', 'Hagen', '(Robe', 'rt Du', 'vall)', ', the', 'Corle', 'one f', 'amily', 'lawye', 'r,', 'are h', 'earin', 'g req', 'uests', 'for f', 'avors', 'becau', 'se, a', 'ccord', 'ing', 'to It', 'alian', 'tradi', 'tion,', 'no Si', 'cilia', 'n can', 'refus', 'e a r', 'eques', 't on', 'his d', 'aught', "er's ", 'weddi', 'ng', 'day.', 'One', 'of', 'the', 'men', 'who', 'asks', 'the', 'Don', 'for a', 'favor', 'is Am', 'erigo', 'Bonas', 'era,', 'a suc', 'cessf', 'ul mo', 'rtici', 'an', 'and a', 'cquai', 'ntanc', 'e of', 'the', 'Don,', 'whose', 'daugh', 'ter', 'was b', 'rutal', 'ly be', 'aten', 'by', 'two', 'young', 'men b', 'ecaus', 'e she', 'refus', 'ed', 'their', 'advan', 'ces;', 'the', 'men r', 'eceiv', 'ed mi', 'nimal', 'punis', 'hment', 'from', 'the p', 'resid', 'ing j', 'udge.', 'The', 'Don', 'is di', 'sappo', 'inted', 'in Bo', 'naser', 'a,', "who'd", 'avoid', 'ed', 'most ', 'conta', 'ct', 'with', 'the', 'Don', 'due', 'to Co', 'rleon', "e's n", 'efari', 'ous b', 'usine', 'ss de', 'aling', 's.', 'The', "Don's", 'wife', 'is go', 'dmoth', 'er to', 'Bonas', "era's", 'shame', 'd dau', 'ghter', ', a r', 'elati', 'onshi', 'p the', 'Don', 'uses', 'to ex', 'tract', 'new l', 'oyalt', 'y', 'from', 'the u', 'ndert', 'aker.', 'The', 'Don a', 'grees', 'to', 'have', 'his', 'men p', 'unish', 'the', 'young', 'men r', 'espon', 'sible', '(in a', 'non-l', 'ethal', 'manne', 'r) in', 'retur', 'n for', 'futur', 'e ser', 'vice', 'if ne', 'cessa', 'ry.']

Text Wrapping Methods

       There are a few techniques in the Textwrap module. These modules are −
1. Module (textwrap.wrap(text, width = 70, **kwargs))
This technique wraps the information passage. It utilizes the line width to wrap the substance. Default line width is 70. It restores a rundown of lines. In the rundown every single wrapped line are put away.
2. Module (textwrap.fill(text, width = 70, **kwargs))
The fill() strategy is like the wrap technique, yet it doesn't produce a rundown. It creates a string. It includes the new line character in the wake of surpassing the predefined width.
3. Module (textwrap.shorten(text, width, **kwargs))
This strategy abbreviates or shortens the string. After truncation the length of the content will be same as the predetermined width. It will include [… ] toward the finish of the string.

Example Code

import textwrap

python_desc = """Python is a general-purpose interpreted, interactive, object-oriented, 
                 and high-level programming language. It was created by Guido van Rossum 
                 during 1985- 1990. Like Perl, Python source code is also available under 
                 the GNU General Public License (GPL). This tutorial gives enough 
                 understanding on Python programming language."""

my_wrap = textwrap.TextWrapper(width = 40)
wrap_list = my_wrap.wrap(text=python_desc)

for line in wrap_list:
   print(line)
    
single_line = """Python is a general-purpose interpreted, interactive, object-oriented, 
                 and high-level programming language."""

print('\n\n' + my_wrap.fill(text = single_line))

short_text = textwrap.shorten(text = python_desc, width=150)
print('\n\n' + my_wrap.fill(text = short_text))

Output

Python is a general-purpose interpreted,
interactive, object-oriented,
and high-level programming language. It
was created by Guido van Rossum
during 1985- 1990. Like Perl, Python
source code is also available under
the GNU General Public License (GPL).
This tutorial gives enough
understanding on Python programming
language.

Python is a general-purpose interpreted,
interactive, object-oriented,
and high-level programming language.

Python is a general-purpose interpreted,
interactive, object-oriented, and high-
level programming language. It was
created by Guido van Rossum [...]
       Therefore in python, the textwrap module is utilized to configuration and wrap plain messages. There are a few choices to arrange the writings by changing the line breaks in the info passage.
I hope you enjoyed reading this article and finally, you came to know about Python - Text wrapping.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…

Submit Review