Python difflib Praxisbeispiel

Für eine Communityseite möchte ich, wenn ein Beitrag geändert wird, dem Vorautor eine E-Mail mit den Änderungen schicken. Die klassische Ausgabe eines Diffs gefällt mir besonders gut. Hier ist ein kleines Beispiel wie das Pythonmodul difflib zu gebrauchen ist:

# -*- coding: utf-8 -*-

import difflib

a = """
Lorem ipsum dolor sit amen, consectetuer adipiscing elit. Nunc ac ante sed
ante imperdiet auctor. Fusce dignissim, magna eu feugiat tincidunt, nibh metus
tincidunt augue, quis ullamcorper lorem pede a ante.
"""

b = """
Lorem ipsum dolor sit amen, consectetuer adipiscing eliot. Nunc ac ante sed
ante imperdiet auctor. Fusce dignissim, magna eu feugiat tincidunt, nibh metus
tincidunt augue, quis ullamcorper lorem pede a onte!
"""

d = difflib.unified_diff(
    a.splitlines(),
    b.splitlines(), 
    'Original',
    'Current',
    lineterm=''
)

print '\n'.join(d)

Und die Ausgabe:

--- Original 
+++ Current 
@@ -1,4 +1,4 @@

-Lorem ipsum dolor sit amen, consectetuer adipiscing elit. Nunc ac ante sed
+Lorem ipsum dolor sit amen, consectetuer adipiscing eliot. Nunc ac ante sed
 ante imperdiet auctor. Fusce dignissim, magna eu feugiat tincidunt, nibh metus
-tincidunt augue, quis ullamcorper lorem pede a ante.
+tincidunt augue, quis ullamcorper lorem pede a onte!

Wer eher nach einer farbigen, detailierten Ausgabe wie bei Trac sucht (hier im Beispiel übernimmt Pygments im Nachhinein das Highlighting), sollte sich auch das HtmlDiff Modul anschauen.


Comments closed

Sorry, new comments are no longer allowed for this entry.

Write me an email if you have feedback or any questions regarding this post. If you found this post useful and just want to say thank you then don't forget that I have an Amazon Wishlist. :-)


↑ to the elevators

© 2001—2010 Martin Mahner. This is an I ♥ Django Project.

Admin | Generated: Fri, 3 Sep 2010 01:52:39 +0200