20

你知道有什么图书馆可以帮助你做到这一点吗?

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

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
4

2 回答 2

28

我就是这样解决的:

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)
于 2009-05-10T14:25:22.553 回答
25

你看过内置的 python 模块difflib吗?看看这个例子

于 2009-05-10T12:54:51.893 回答