gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:43:41 25 4
gpt4 key购买 nike

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

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

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

最佳答案

我就是这样解决的:

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)

关于python - 如何以统一的差异格式打印两个多行字符串的比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/845276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com