[英]How to print the comparison of two multiline strings in unified diff format?
您知道有任何图书馆可以帮助您做到这一点吗?
我将编写一个函数,以统一的diff格式打印两个多行字符串之间的差异。 像这样:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.