如何以统一的差异格式打印两个多行字符串的比较?

23

你知道有哪些库可以帮助做到这一点吗?

我会编写一个函数,以统一的差异格式打印两个多行字符串之间的差异。类似于这样:

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

以下是一个用法示例:

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)

这应该打印出类似这样的东西:

--- 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
2个回答

32

这是我的解决方案:

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)

这段代码的功能是正确的,除非差异是一个空行。 "hello\nthere" != "hello\nthere\n"。使用expected = [line for line in expected.split('\n')]可以解决这个问题。 - Marcel Wilson

26

你是否看过Python内置模块difflib?可以参考这个示例


那个链接的例子非常完美。 - Pierre D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接