4.4.4 Esempio di Differ

Questo esempio confronta due testi. Prima impostiamo i testi, sequenze di stringhe individuali composte da una singola riga, e terminanti con un fine riga (queste sequenze possono anche venire ottenute dal metodo readlines() degli oggetti di tipo file):

>>> text1 = '''  1. Beautiful is better than ugly.
...   2. Explicit is better than implicit.
...   3. Simple is better than complex.
...   4. Complex is better than complicated.
... '''.splitlines(1)
>>> len(text1)
4
>>> text1[0][-1]
'\n'
>>> text2 = '''  1. Beautiful is better than ugly.
...   3.   Simple is better than complex.
...   4. Complicated is better than complex.
...   5. Flat is better than nested.
... '''.splitlines(1)

Successivamente istanziamo un oggetto di tipo Differ:

>>> d = Differ()

Notate che quando istanziamo un oggetto di tipo Differ, possiamo passare delle funzioni per filtrare righe e caratteri ``spazzatura''. Vedete il costruttore Differ() per i dettagli.

Infine, confrontiamo le due stringhe:

>>> result = list(d.compare(text1, text2))

result è una lista di stringhe, perciò stampiamole graziosamente:

>>> from pprint import pprint
>>> pprint(result)
['    1. Beautiful is better than ugly.\n',
 '-   2. Explicit is better than implicit.\n',
 '-   3. Simple is better than complex.\n',
 '+   3.   Simple is better than complex.\n',
 '?     ++                                \n',
 '-   4. Complex is better than complicated.\n',
 '?            ^                     ---- ^  \n',
 '+   4. Complicated is better than complex.\n',
 '?           ++++ ^                      ^  \n',
 '+   5. Flat is better than nested.\n']

Come una singola stringa di più righe, appare così:

>>> import sys
>>> sys.stdout.writelines(result)
    1. Beautiful is better than ugly.
-   2. Explicit is better than implicit.
-   3. Simple is better than complex.
+   3.   Simple is better than complex.
?     ++
-   4. Complex is better than complicated.
?            ^                     ---- ^
+   4. Complicated is better than complex.
?           ++++ ^                      ^
+   5. Flat is better than nested.
Vedete Circa questo documento... per informazioni su modifiche e suggerimenti.