2009-05-10 9 views
13

¿Conoces alguna biblioteca que te ayude a hacer eso?¿Cómo se imprime la comparación de dos cadenas de líneas múltiples en formato de diff unificado?

Escribiría una función que imprime las diferencias entre dos cadenas de líneas múltiples en el formato de diff unificado. Algo así:

def print_differences(string1, string2): 
    """ 
    Prints the comparison of string1 to string2 as unified diff format. 
    """ 
    ??? 

Un ejemplo de uso es el siguiente:

string1=""" 
Usage: trash-empty [days] 

Purge trashed files. 

Options: 
    --version show program's version number and exit 
    -h, --help show this help message and exit 
""" 

string2=""" 
Usage: trash-empty [days] 

Empty the trash can. 

Options: 
    --version show program's version number and exit 
    -h, --help show this help message and exit 

Report bugs to http://code.google.com/p/trash-cli/issues 
""" 

print_differences(string1, string2) 

Esto debería imprimir algo así:

--- string1 
+++ string2 
@@ -1,6 +1,6 @@ 
Usage: trash-empty [days] 

-Purge trashed files. 
+Empty the trash can. 

Options: 
    --version show program's version number and exit 

Respuesta

18

Así es como he resuelto:

def _unidiff_output(expected, actual): 
    """ 
    Helper function. Returns a string containing the unified diff of two multiline strings. 
    """ 

    import difflib 
    expected=expected.splitlines(1) 
    actual=actual.splitlines(1) 

    diff=difflib.unified_diff(expected, actual) 

    return ''.join(diff) 
18

¿Tuvo un vistazo a la incorporada en el pitón módulo difflib? un vistazo que esta example

Cuestiones relacionadas