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

23 投票
2 回答
28685 浏览
提问于 2025-04-15 11:29

你知道有什么库可以帮助实现这个功能吗?

我想写一个函数,用来打印两个多行字符串之间的差异,格式是统一差异格式。大概是这样的:

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

26

你有没有看看Python自带的一个模块叫做difflib?可以看看这个例子

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)

撰写回答