textwrap - Formatta paragrafi di testo

Scopo Formatta il testo sistemando le interruzioni di riga in un paragrafo
Versione Python 2.5

Il modulo textwrap può essere usto per formattare il testo in uscita dove necessiti una stampa pretty-printing. Fornisce funzionalità programmatiche simili a quelle di wrap o distribuzione testo del paragrafo, comuni a molti editor di testo.

Dati di Esempio

Gli esempi di seguito usano textwrap_exmaple.py , che contiene una stringa sample_text :

sample_text = '''
	The textwrap module can be used to format text for output in situations
	where pretty-printing is desired.  It offers programmatic functionality similar
	to the paragraph wrapping or filling features found in many text editors.
	'''

Riempire Paragrafi

La funzione fill() prende in testo in input e produce testo formattato in uscita. Ecco cosa fa con il testo fornito da sample_text

import textwrap
from textwrap_example import sample_text

print 'Nessuna deindentazione:\n'
print textwrap.fill(sample_text)

I risultati non sono quelli che avremmo voluto:

$ python textwrap_fill.py
Nessuna deindentazione:

         The textwrap module can be used to format text for output in
situations         where pretty-printing is desired.  It offers
programmatic functionality similar         to the paragraph wrapping
or filling features found in many text editors.

Rimuovere Indentazione Esistente

Si notino i caratteri di tabulazione all'interno delle righe e gli spazi aggiuntivi iniziali mescolati nel mezzo dell'ouput. Sembra piuttosto rozzo. Naturalmente si può fare di meglio. Si potrebbe iniziare eliminando tutti gli spazi che precedono ogni riga nel testo di esempio. Questo consente di usare le docstring oppure le stringhe multiriga incorporate direttamente dal proprio codice Python senza eliminare la formattazione del codice stesso. La stringa di esempio ha un livello di indentazione artificiale introdotto per illustrare questa caratteristica.

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text).strip()
print 'Deindentato:\n'
print dedented_text

Il risultato inizia ad avere un aspetto migliore

$ python textwrap_dedent.py
Deindentato:

The textwrap module can be used to format text for output in situations
where pretty-printing is desired.  It offers programmatic functionality similar
to the paragraph wrapping or filling features found in many text editors.

Visto che la "deindentazione" è il contrario dell'indentazione, il risultato è un blocco di testo con gli spazi iniziali di ogni riga rimossi. Se una riga ha già una indentazione superiore alle altre alcuni degli spazi non saranno eliminati.

 One tab.
 Two tabs.
One tab.

diventa

One tab.
Two tabs.
One tab.

Combinare Dedent e Fill

Proseguendo, ecco cosa accade se si prende il testo deindentato e lo si passa attraverso fill() con diversi valori di larghezza.

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text).strip()
for width in [ 20, 60, 80 ]:
	print
	print '%d Colonne:\n' % width
	print textwrap.fill(dedented_text, width=width)

Si otterranno diversi tipi di ouput della larghezza specificata

$ python textwrap_fill_width.py

20 Colonne:

The textwrap module
can be used to
format text for
output in situations
where pretty-
printing is desired.
It offers
programmatic
functionality
similar to the
paragraph wrapping
or filling features
found in many text
editors.

60 Colonne:

The textwrap module can be used to format text for output in
situations where pretty-printing is desired.  It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.

80 Colonne:

The textwrap module can be used to format text for output in situations where
pretty-printing is desired.  It offers programmatic functionality similar to the
paragraph wrapping or filling features found in many text editors.

Indentazioni Sospese

A parte la larghezza dell'output, si può controllare l'indentazione della prima riga indipendentemente da quelle successive.

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text).strip()
print textwrap.fill(dedented_text, initial_indent='', subsequent_indent='    ')

Questo rende relativamente semplice produrre una indentazione sospesa, dove la prima riga è indentata meno che le altre righe

$ python textwrap_hanging_indent.py
The textwrap module can be used to format text for output in
    situations where pretty-printing is desired.  It offers
    programmatic functionality similar to the paragraph wrapping or
    filling features found in many text editors.

I valori di indentazione possono anche includere caratteri diversi dallo spazio, così che l'indentazione sospesa possa essere prefissata da un * per ottenere elementi puntati, etc. Questo mi tornò comodo quando dovetti convertire il contenuto del mio vecchio zwiki per importarlo in trac. Ho usato il pacchetto StructuredText da Zope per analizzare i dati da zwiki, quindi ho creato un formattatore per produrre il marcatore del trac di wiki come risultato. Usando textwrap , sono poi stato capace di formattare le pagine di output senza che quasi nessun intervento manuale sia stato necessario dopo la conversione.

Vedere anche:

textwrap
La documentazione della libreria standard per questo modulo.
Strumenti di Elaborazione del Testo